Compare commits

..

35 Commits

Author SHA1 Message Date
c5e7a5eb08 Add support for CA bundles (#885)
Why:

- Allow CA cert bundles to be used

This change addresses the need by:

- Adding a constructor that takes a pointer to the bundle
- Setting the WiFiClientSecure to use the bundle
- Adding an example
2024-06-17 13:09:37 +02:00
93707d455f fix build_sketch_cli result handling 2024-01-05 17:28:16 +01:00
8d193b176d [Prevent unwanted Compiler Warnings]: Issue #772 - wrong format specifier in line 754 (#773)
* [Prevent unwanted Compiler Warnings]: Issue #772
2024-01-05 17:25:57 +01:00
503105a9fe Remove compiler warnings (#854)
* [Prevent unwanted Compiler Warnings]: Issue #772
2024-01-05 17:24:45 +01:00
6a26f74f95 code style 2024-01-05 15:27:49 +01:00
be9fd8e267 fix getSocketNumber for ESP 2024-01-05 15:26:59 +01:00
313f2e0170 update actions/cache@v3 2024-01-05 15:26:26 +01:00
3b143bc6f3 🐛 removed default values from *.cpp file 2024-01-05 15:20:03 +01:00
aed167bee0 updated the header file for the same changes 2024-01-05 15:20:03 +01:00
4acc33589a added option arguments in socket io being, for pingInterval, pongTimeout, and disconnectTimeoutCount 2024-01-05 15:20:03 +01:00
3352c833b8 - Fix memory leak by calling delete _server in the WebSocketsServer destructor.
- Improve performance by looking for match to existing socket before creating a new one
2024-01-05 15:17:42 +01:00
241c73a806 use ARDUINO_BOARD_MANAGER_ADDITIONAL_URLS env for setting board URLs 2024-01-05 15:06:30 +01:00
437c0252f1 fix cli download URL 2024-01-05 15:01:53 +01:00
92480b8987 IDE_VERSION --> CLI_VERSION 2024-01-05 15:00:16 +01:00
da7efc789e update github actions to arduino-cli for build tests 2024-01-05 14:57:05 +01:00
30d5e13666 set minimum bufsize for base64 encode 2023-08-19 21:16:37 +02:00
751cf87b6c feat(socketio): add disconnect function 2023-05-23 18:03:07 +02:00
a215cca4fe bump version 2.4.1 2023-05-01 15:02:36 +02:00
bb900a77b6 GITHUB_STATE --> GITHUB_OUTPUT 2023-05-01 14:53:30 +02:00
7eda34f345 add RP2040 as supported and bump version 2023-05-01 14:51:36 +02:00
22dff6598f make OTA work with ArduinoJson 6.x 2023-05-01 14:48:18 +02:00
a4f13a1410 clang-format 2023-05-01 14:36:26 +02:00
4115a87c16 set-output command is deprecated 2023-05-01 14:36:07 +02:00
82c357c036 fix OTA example build and build tests for esp8266 examples 2023-05-01 14:30:20 +02:00
d9a5c629f0 Port to Raspberry Pi Pico W core
Add support for the onboard WiFi chip on the Raspberry Pi Pico W
(RP2040 based ) board using the arduino-pico Arduino core at
https://github.com/earlephilhower/arduino-pico

The PicoW WiFi stack is a mashup of the ESP8266 and ESP32 cores, so
only minimal changes were required.  Defines a new NETWORK_TYPE for
the PicoW.

ESP8266 examples renames to ESP8266_PICO because they all work unmodified
(except for OTA which is handled differently on the Pico)
2023-05-01 08:50:01 +02:00
323592f622 Add possibility to change WEBSOCKETS_TCP_TIMEOUT 2022-08-22 14:28:19 +02:00
f1ffaede0b Fix Typo 2022-08-22 14:22:00 +02:00
94a531c464 Use async sleep, increase chunk size 2022-08-22 14:22:00 +02:00
ccdba4ed8a Fix response type prefix (LoadProhibitedCause) 2022-08-22 14:22:00 +02:00
2b0e8f6fe9 Fix async run 2022-08-22 14:22:00 +02:00
dd8675c6a9 don't update cSessionId on unwanted Set-Cookie 2022-06-24 10:57:33 +02:00
2110ad0a10 more debug 2022-06-24 10:54:26 +02:00
04249a9b62 more debug 2022-06-24 10:54:26 +02:00
1fb67c8868 esp8266 build, change config options 2022-06-24 10:54:26 +02:00
3073c156b1 Fix compiler warning "function may return address of local variable" 2022-06-24 10:26:43 +02:00
46 changed files with 4450 additions and 156 deletions

View File

@ -33,18 +33,20 @@ jobs:
run: |
source $GITHUB_WORKSPACE/travis/common.sh
cd $GITHUB_WORKSPACE
echo -en "::set-output name=matrix::"
echo -en "["
get_sketches_json_matrix arduino $GITHUB_WORKSPACE/examples/esp8266 esp8266 1.8.19 esp8266com:esp8266:generic:xtal=80,vt=flash,exception=disabled,stacksmash=disabled,ssl=all,mmu=3232,non32xfer=fast,ResetMethod=nodemcu,CrystalFreq=26,FlashFreq=80,FlashMode=qio,eesz=4M2M,led=2,sdk=nonosdk_190703,ip=lm2f,dbg=Serial1,lvl=SSL,wipe=none,baud=115200
echo -en ","
echo -en "matrix=" >> $GITHUB_OUTPUT
echo -en "[" >> $GITHUB_OUTPUT
get_sketches_json_matrix arduino $GITHUB_WORKSPACE/examples/esp8266 esp8266 1.8.19 esp8266com:esp8266:generic:xtal=80,vt=flash,exception=disabled,stacksmash=disabled,ssl=all,mmu=3232,non32xfer=fast,ResetMethod=nodemcu,CrystalFreq=26,FlashFreq=80,FlashMode=qio,eesz=4M2M,led=2,sdk=nonosdk_190703,ip=lm2f,dbg=Disabled,lvl=None____,wipe=none,baud=115200
echo -en ","
get_sketches_json_matrix arduino $GITHUB_WORKSPACE/examples/esp8266_pico esp8266 0.35.0 esp8266:esp8266:generic:xtal=80,vt=flash,exception=disabled,stacksmash=disabled,ssl=all,mmu=3232,non32xfer=fast,ResetMethod=nodemcu,CrystalFreq=26,FlashFreq=80,FlashMode=qio,eesz=4M2M,led=2,sdk=nonosdk_190703,ip=lm2f,dbg=Serial1,lvl=SSL,wipe=none,baud=115200 >> $GITHUB_OUTPUT
echo -en "," >> $GITHUB_OUTPUT
get_sketches_json_matrix arduino $GITHUB_WORKSPACE/examples/esp32 esp32 1.8.19 espressif:esp32:esp32:FlashFreq=80
get_sketches_json_matrix arduino $GITHUB_WORKSPACE/examples/esp8266_pico esp8266 0.35.0 esp8266:esp8266:generic:xtal=80,vt=flash,exception=disabled,stacksmash=disabled,ssl=all,mmu=3232,non32xfer=fast,ResetMethod=nodemcu,CrystalFreq=26,FlashFreq=80,FlashMode=qio,eesz=4M2M,led=2,sdk=nonosdk_190703,ip=lm2f,dbg=Disabled,lvl=None____,wipe=none,baud=115200 >> $GITHUB_OUTPUT
echo -en "," >> $GITHUB_OUTPUT
echo -en "]"
get_sketches_json_matrix arduino $GITHUB_WORKSPACE/examples/esp32 esp32 0.35.0 esp32:esp32:esp32:FlashFreq=80 >> $GITHUB_OUTPUT
echo -en "]" >> $GITHUB_OUTPUT
echo >> $GITHUB_OUTPUT
outputs:
matrix: ${{ steps.set-matrix.outputs.matrix }}
@ -53,9 +55,10 @@ jobs:
strategy:
fail-fast: false
matrix:
IDE_VERSION: [1.8.19]
CLI_VERSION: [0.35.0]
env:
IDE_VERSION: ${{ matrix.IDE_VERSION }}
CLI_VERSION: ${{ matrix.CLI_VERSION }}
ARDUINO_DIRECTORIES_DATA: /home/runner/arduino_ide
steps:
- uses: actions/checkout@v2
@ -63,23 +66,24 @@ jobs:
- name: Get Date
id: get-date
run: |
echo "::set-output name=date::$(/bin/date -u "+%Y%m%d")"
echo "date=$(/bin/date -u "+%Y%m%d")" >> $GITHUB_OUTPUT
shell: bash
- uses: actions/cache@v2
- uses: actions/cache@v3
id: cache_all
with:
path: |
/home/runner/arduino_ide
/home/runner/Arduino
key: ${{ runner.os }}-${{ steps.get-date.outputs.date }}-${{ matrix.IDE_VERSION }}
key: ${{ runner.os }}-${{ steps.get-date.outputs.date }}-${{ matrix.CLI_VERSION }}-cli
- name: download IDE
if: steps.cache_all.outputs.cache-hit != 'true'
run: |
wget http://downloads.arduino.cc/arduino-$IDE_VERSION-linux64.tar.xz -q
tar xf arduino-$IDE_VERSION-linux64.tar.xz
mv arduino-$IDE_VERSION $HOME/arduino_ide
wget https://github.com/arduino/arduino-cli/releases/download/v${CLI_VERSION}/arduino-cli_${CLI_VERSION}_Linux_64bit.tar.gz -q
tar xf arduino-cli_${CLI_VERSION}_Linux_64bit.tar.gz
mkdir -p $ARDUINO_DIRECTORIES_DATA
mv arduino-cli $ARDUINO_DIRECTORIES_DATA/
- name: download ArduinoJson
if: steps.cache_all.outputs.cache-hit != 'true'
@ -89,17 +93,12 @@ jobs:
unzip 6.x.zip
mv ArduinoJson-6.x $HOME/Arduino/libraries/ArduinoJson
- name: download esp8266
- name: download cores
if: steps.cache_all.outputs.cache-hit != 'true'
run: |
export PATH="$ARDUINO_DIRECTORIES_DATA:$PATH"
source $GITHUB_WORKSPACE/travis/common.sh
get_core esp8266
- name: download esp32
if: steps.cache_all.outputs.cache-hit != 'true'
run: |
source $GITHUB_WORKSPACE/travis/common.sh
get_core esp32
get_core_cli
build:
needs: [prepare_ide, prepare_example_json]
@ -111,8 +110,9 @@ jobs:
env:
CPU: ${{ matrix.cpu }}
BOARD: ${{ matrix.board }}
IDE_VERSION: ${{ matrix.ideversion }}
CLI_VERSION: ${{ matrix.cliversion }}
SKETCH: ${{ matrix.sketch }}
ARDUINO_DIRECTORIES_DATA: /home/runner/arduino_ide
# Steps represent a sequence of tasks that will be executed as part of the job
steps:
@ -125,16 +125,16 @@ jobs:
- name: Get Date
id: get-date
run: |
echo "::set-output name=date::$(/bin/date -u "+%Y%m%d")"
echo "date=$(/bin/date -u "+%Y%m%d")" >> $GITHUB_OUTPUT
shell: bash
- uses: actions/cache@v2
- uses: actions/cache@v3
id: cache_all
with:
path: |
/home/runner/arduino_ide
/home/runner/Arduino
key: ${{ runner.os }}-${{ steps.get-date.outputs.date }}-${{ matrix.ideversion }}
key: ${{ runner.os }}-${{ steps.get-date.outputs.date }}-${{ matrix.cliversion }}-cli
- name: install python serial
if: matrix.cpu == 'esp32'
@ -143,41 +143,24 @@ jobs:
sudo pip install pyserial
# sudo apt install python-is-python3
- name: start DISPLAY
run: |
/sbin/start-stop-daemon --start --quiet --pidfile /tmp/custom_xvfb_1.pid --make-pidfile --background --exec /usr/bin/Xvfb -- :1 -ac -screen 0 1280x1024x16
export DISPLAY=:1.0
sleep 3
- name: test IDE
run: |
export PATH="$HOME/arduino_ide:$PATH"
which arduino
export PATH="$ARDUINO_DIRECTORIES_DATA:$PATH"
which arduino-cli
- name: copy code
run: |
mkdir -p $HOME/Arduino/libraries/
cp -r $GITHUB_WORKSPACE $HOME/Arduino/libraries/arduinoWebSockets
- name: config IDE
run: |
set +x
export DISPLAY=:1.0
export PATH="$HOME/arduino_ide:$PATH"
arduino --board $BOARD --save-prefs
arduino --pref update.check=false --pref build.verbose=false --pref cache.enable=true --pref compiler.cache_core=true --pref compiler.warning_level=default --save-prefs
arduino --get-pref sketchbook.path
arduino --get-pref
- name: build example
timeout-minutes: 20
run: |
set -ex
export DISPLAY=:1.0
export PATH="$HOME/arduino_ide:$PATH"
source $GITHUB_WORKSPACE/travis/common.sh
cd $GITHUB_WORKSPACE
build_sketch arduino $SKETCH
build_sketch_cli "$SKETCH" "$BOARD"
done:
needs: [prepare_ide, prepare_example_json, build, check_version_files]

View File

@ -26,6 +26,7 @@ a WebSocket Server and Client for Arduino based on RFC6455.
- ESP8266 [Arduino for ESP8266](https://github.com/esp8266/Arduino/)
- ESP32 [Arduino for ESP32](https://github.com/espressif/arduino-esp32)
- ESP31B
- Raspberry Pi Pico W [Arduino for Pico](https://github.com/earlephilhower/arduino-pico)
- Particle with STM32 ARM Cortex M3
- ATmega328 with Ethernet Shield (ATmega branch)
- ATmega328 with enc28j60 (ATmega branch)
@ -47,6 +48,16 @@ a WebSocket Server and Client for Arduino based on RFC6455.
by running the device behind an SSL proxy. See [Nginx](examples/Nginx/esp8266.ssl.reverse.proxy.conf) for a
sample Nginx server configuration file to enable this.
### Root CA Cert Bundles for SSL/TLS connections ###
Secure connections require the certificate of the server to be verified. One option is to provide a single certificate in the chain of trust. However, for flexibility and robustness, a certificate bundle is recommended. If a server changes the root CA from which it derives its certificates, this will not be a problem. With a single CA cert it will not connect.
- For [technical details](https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/protocols/esp_crt_bundle.html)
- For a [PlatformIO setup](https://github.com/Duckle29/esp32-certBundle/)
- For an [example](examples/esp32/WebSocketClientSSLBundle/)
Including a bundle with all CA certs will use 77.2 kB but this list can be reduced to 16.5 kB for the 41 most common. This results in 90% absolute usage coverage and 99% market share coverage according to [W3Techs](https://w3techs.com/technologies/overview/ssl_certificate). The bundle is inserted into the compiled firmware. The bundle is not loaded into RAM, only its index.
### ESP Async TCP ###
This libary can run in Async TCP mode on the ESP.

View File

@ -0,0 +1,129 @@
/*
* main.cpp
*
* Created on: 15.06.2024
*
*/
#include <Arduino.h>
#include <WiFi.h>
#include <WiFiMulti.h>
#include <WebSocketsClient.h>
// Use the incbin library to embedd the cert binary
// extern const uint8_t rootca_crt_bundle_start[] asm(
// "_binary_data_cert_x509_crt_bundle_bin_start");
WiFiMulti wifiMulti;
WebSocketsClient webSocket;
#define USE_SERIAL Serial
void setClock() {
configTime(0, 0, "pool.ntp.org", "time.nist.gov");
USE_SERIAL.print(F("Waiting for NTP time sync: "));
time_t nowSecs = time(nullptr);
while(nowSecs < 8 * 3600 * 2) {
delay(500);
USE_SERIAL.print(F("."));
yield();
nowSecs = time(nullptr);
}
USE_SERIAL.println();
struct tm timeinfo;
gmtime_r(&nowSecs, &timeinfo);
USE_SERIAL.print(F("Current time: "));
USE_SERIAL.print(asctime(&timeinfo));
}
void hexdump(const void * mem, uint32_t len, uint8_t cols = 16) {
const uint8_t * src = (const uint8_t *)mem;
USE_SERIAL.printf("\n[HEXDUMP] Address: 0x%08X len: 0x%X (%d)", (ptrdiff_t)src, len, len);
for(uint32_t i = 0; i < len; i++) {
if(i % cols == 0) {
USE_SERIAL.printf("\n[0x%08X] 0x%08X: ", (ptrdiff_t)src, i);
}
USE_SERIAL.printf("%02X ", *src);
src++;
}
USE_SERIAL.printf("\n");
}
void webSocketEvent(WStype_t type, uint8_t * payload, size_t length) {
switch(type) {
case WStype_DISCONNECTED:
USE_SERIAL.printf("[WSc] Disconnected!\n");
break;
case WStype_CONNECTED:
USE_SERIAL.printf("[WSc] Connected to url: %s\n", payload);
// send message to server when Connected
webSocket.sendTXT("Connected");
break;
case WStype_TEXT:
USE_SERIAL.printf("[WSc] get text: %s\n", payload);
// send message to server
// webSocket.sendTXT("message here");
break;
case WStype_BIN:
USE_SERIAL.printf("[WSc] get binary length: %u\n", length);
hexdump(payload, length);
// send data to server
// webSocket.sendBIN(payload, length);
break;
case WStype_ERROR:
case WStype_FRAGMENT_TEXT_START:
case WStype_FRAGMENT_BIN_START:
case WStype_FRAGMENT:
case WStype_FRAGMENT_FIN:
break;
}
}
void setup() {
USE_SERIAL.begin(115200);
USE_SERIAL.setDebugOutput(true);
USE_SERIAL.println();
USE_SERIAL.println();
USE_SERIAL.println();
for(uint8_t t = 4; t > 0; t--) {
USE_SERIAL.printf("[SETUP] BOOT WAIT %d...\n", t);
USE_SERIAL.flush();
delay(1000);
}
wifiMulti.addAP("SSID", "WIFI_PASSPHRASE");
// WiFi.disconnect();
while(wifiMulti.run() != WL_CONNECTED) {
delay(100);
}
setClock();
// server address, port and URL. This server can be flakey.
// Expected response: Request served by 0123456789abcdef
// webSocket.beginSslWithBundle("echo.websocket.org", 443, "/", rootca_crt_bundle_start, "");
webSocket.beginSslWithBundle("echo.websocket.org", 443, "/", NULL, "");
// event handler
webSocket.onEvent(webSocketEvent);
// use HTTP Basic Authorization this is optional enable if needed
// webSocket.setAuthorization("user", "Password");
// try ever 5000 again if connection has failed
webSocket.setReconnectInterval(5000);
}
void loop() {
webSocket.loop();
}

View File

@ -0,0 +1,8 @@
.pio
.vscode/.browse.c_cpp.db*
.vscode/c_cpp_properties.json
.vscode/launch.json
.vscode/ipch
*secret*
!*secrets.hpp.template
*x509_crt_bundle.bin

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,39 @@
Owner,Common Name or Certificate Name
Amazon Trust Services,Amazon Root CA 1
Amazon Trust Services,Amazon Root CA 2
Amazon Trust Services,Amazon Root CA 3
Amazon Trust Services,Amazon Root CA 4
Amazon Trust Services,Starfield Services Root Certificate Authority - G2
DigiCert,Baltimore CyberTrust Root
DigiCert,Cybertrust Global Root
DigiCert,DigiCert Assured ID Root CA
DigiCert,DigiCert Assured ID Root G2
DigiCert,DigiCert Assured ID Root G3
DigiCert,DigiCert Global Root CA
DigiCert,DigiCert Global Root G2
DigiCert,DigiCert Global Root G3
DigiCert,DigiCert High Assurance EV Root CA
DigiCert,DigiCert Trusted Root G4
GlobalSign,GlobalSign ECC Root CA - R5
GlobalSign,GlobalSign Root CA - R3
GlobalSign,GlobalSign Root CA - R6
GlobalSign,GlobalSign Root CA
GoDaddy,Go Daddy Class 2 CA
GoDaddy,Go Daddy Root Certificate Authority - G2
GoDaddy,Starfield Class 2 CA
GoDaddy,Starfield Root Certificate Authority - G2
Google Trust Services LLC (GTS),GlobalSign ECC Root CA - R4
Google Trust Services LLC (GTS),GlobalSign Root CA - R2
Google Trust Services LLC (GTS),GTS Root R1
Google Trust Services LLC (GTS),GTS Root R2
Google Trust Services LLC (GTS),GTS Root R3
Google Trust Services LLC (GTS),GTS Root R4
"IdenTrust Services, LLC",DST Root CA X3
"IdenTrust Services, LLC",IdenTrust Commercial Root CA 1
"IdenTrust Services, LLC",IdenTrust Public Sector Root CA 1
Sectigo,Comodo AAA Services root
Sectigo,COMODO Certification Authority
Sectigo,COMODO ECC Certification Authority
Sectigo,COMODO RSA Certification Authority
Sectigo,USERTrust ECC Certification Authority
Sectigo,USERTrust RSA Certification Authority
1 Owner Common Name or Certificate Name
2 Amazon Trust Services Amazon Root CA 1
3 Amazon Trust Services Amazon Root CA 2
4 Amazon Trust Services Amazon Root CA 3
5 Amazon Trust Services Amazon Root CA 4
6 Amazon Trust Services Starfield Services Root Certificate Authority - G2
7 DigiCert Baltimore CyberTrust Root
8 DigiCert Cybertrust Global Root
9 DigiCert DigiCert Assured ID Root CA
10 DigiCert DigiCert Assured ID Root G2
11 DigiCert DigiCert Assured ID Root G3
12 DigiCert DigiCert Global Root CA
13 DigiCert DigiCert Global Root G2
14 DigiCert DigiCert Global Root G3
15 DigiCert DigiCert High Assurance EV Root CA
16 DigiCert DigiCert Trusted Root G4
17 GlobalSign GlobalSign ECC Root CA - R5
18 GlobalSign GlobalSign Root CA - R3
19 GlobalSign GlobalSign Root CA - R6
20 GlobalSign GlobalSign Root CA
21 GoDaddy Go Daddy Class 2 CA
22 GoDaddy Go Daddy Root Certificate Authority - G2
23 GoDaddy Starfield Class 2 CA
24 GoDaddy Starfield Root Certificate Authority - G2
25 Google Trust Services LLC (GTS) GlobalSign ECC Root CA - R4
26 Google Trust Services LLC (GTS) GlobalSign Root CA - R2
27 Google Trust Services LLC (GTS) GTS Root R1
28 Google Trust Services LLC (GTS) GTS Root R2
29 Google Trust Services LLC (GTS) GTS Root R3
30 Google Trust Services LLC (GTS) GTS Root R4
31 IdenTrust Services, LLC DST Root CA X3
32 IdenTrust Services, LLC IdenTrust Commercial Root CA 1
33 IdenTrust Services, LLC IdenTrust Public Sector Root CA 1
34 Sectigo Comodo AAA Services root
35 Sectigo COMODO Certification Authority
36 Sectigo COMODO ECC Certification Authority
37 Sectigo COMODO RSA Certification Authority
38 Sectigo USERTrust ECC Certification Authority
39 Sectigo USERTrust RSA Certification Authority

View File

@ -0,0 +1,227 @@
#!/usr/bin/env python
#
# ESP32 x509 certificate bundle generation utility
#
# Converts PEM and DER certificates to a custom bundle format which stores just the
# subject name and public key to reduce space
#
# The bundle will have the format: number of certificates; crt 1 subject name length; crt 1 public key length;
# crt 1 subject name; crt 1 public key; crt 2...
#
# Copyright 2018-2019 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.
from __future__ import with_statement
import argparse
import csv
import os
import re
import struct
import sys
from io import open
try:
from cryptography import x509
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
except ImportError:
print('The cryptography package is not installed.'
'Please refer to the Get Started section of the ESP-IDF Programming Guide for '
'setting up the required packages.')
raise
ca_bundle_bin_file = 'x509_crt_bundle'
quiet = False
def status(msg):
""" Print status message to stderr """
if not quiet:
critical(msg)
def critical(msg):
""" Print critical message to stderr """
sys.stderr.write('gen_crt_bundle.py: ')
sys.stderr.write(msg)
sys.stderr.write('\n')
class CertificateBundle:
def __init__(self):
self.certificates = []
self.compressed_crts = []
if os.path.isfile(ca_bundle_bin_file):
os.remove(ca_bundle_bin_file)
def add_from_path(self, crts_path):
found = False
for file_path in os.listdir(crts_path):
found |= self.add_from_file(os.path.join(crts_path, file_path))
if found is False:
raise InputError('No valid x509 certificates found in %s' % crts_path)
def add_from_file(self, file_path):
try:
if file_path.endswith('.pem'):
status('Parsing certificates from %s' % file_path)
with open(file_path, 'r', encoding='utf-8') as f:
crt_str = f.read()
self.add_from_pem(crt_str)
return True
elif file_path.endswith('.der'):
status('Parsing certificates from %s' % file_path)
with open(file_path, 'rb') as f:
crt_str = f.read()
self.add_from_der(crt_str)
return True
except ValueError:
critical('Invalid certificate in %s' % file_path)
raise InputError('Invalid certificate')
return False
def add_from_pem(self, crt_str):
""" A single PEM file may have multiple certificates """
crt = ''
count = 0
start = False
for strg in crt_str.splitlines(True):
if strg == '-----BEGIN CERTIFICATE-----\n' and start is False:
crt = ''
start = True
elif strg == '-----END CERTIFICATE-----\n' and start is True:
crt += strg + '\n'
start = False
self.certificates.append(x509.load_pem_x509_certificate(crt.encode(), default_backend()))
count += 1
if start is True:
crt += strg
if(count == 0):
raise InputError('No certificate found')
status('Successfully added %d certificates' % count)
def add_from_der(self, crt_str):
self.certificates.append(x509.load_der_x509_certificate(crt_str, default_backend()))
status('Successfully added 1 certificate')
def create_bundle(self):
# Sort certificates in order to do binary search when looking up certificates
self.certificates = sorted(self.certificates, key=lambda cert: cert.subject.public_bytes(default_backend()))
bundle = struct.pack('>H', len(self.certificates))
for crt in self.certificates:
""" Read the public key as DER format """
pub_key = crt.public_key()
pub_key_der = pub_key.public_bytes(serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo)
""" Read the subject name as DER format """
sub_name_der = crt.subject.public_bytes(default_backend())
name_len = len(sub_name_der)
key_len = len(pub_key_der)
len_data = struct.pack('>HH', name_len, key_len)
bundle += len_data
bundle += sub_name_der
bundle += pub_key_der
return bundle
def add_with_filter(self, crts_path, filter_path):
filter_set = set()
with open(filter_path, 'r', encoding='utf-8') as f:
csv_reader = csv.reader(f, delimiter=',')
# Skip header
next(csv_reader)
for row in csv_reader:
filter_set.add(row[1])
status('Parsing certificates from %s' % crts_path)
crt_str = []
with open(crts_path, 'r', encoding='utf-8') as f:
crt_str = f.read()
# Split all certs into a list of (name, certificate string) tuples
pem_crts = re.findall(r'(^.+?)\n(=+\n[\s\S]+?END CERTIFICATE-----\n)', crt_str, re.MULTILINE)
filtered_crts = ''
for name, crt in pem_crts:
if name in filter_set:
filtered_crts += crt
self.add_from_pem(filtered_crts)
class InputError(RuntimeError):
def __init__(self, e):
super(InputError, self).__init__(e)
def main():
global quiet
parser = argparse.ArgumentParser(description='ESP-IDF x509 certificate bundle utility')
parser.add_argument('--quiet', '-q', help="Don't print non-critical status messages to stderr", action='store_true')
parser.add_argument('--input', '-i', nargs='+', required=True,
help='Paths to the custom certificate folders or files to parse, parses all .pem or .der files')
parser.add_argument('--filter', '-f', help='Path to CSV-file where the second columns contains the name of the certificates \
that should be included from cacrt_all.pem')
args = parser.parse_args()
quiet = args.quiet
bundle = CertificateBundle()
for path in args.input:
if os.path.isfile(path):
if os.path.basename(path) == 'cacrt_all.pem' and args.filter:
bundle.add_with_filter(path, args.filter)
else:
bundle.add_from_file(path)
elif os.path.isdir(path):
bundle.add_from_path(path)
else:
raise InputError('Invalid --input=%s, is neither file nor folder' % args.input)
status('Successfully added %d certificates in total' % len(bundle.certificates))
crt_bundle = bundle.create_bundle()
with open(ca_bundle_bin_file, 'wb') as f:
f.write(crt_bundle)
if __name__ == '__main__':
try:
main()
except InputError as e:
print(e)
sys.exit(2)

View File

@ -0,0 +1,46 @@
This directory is intended for project specific (private) libraries.
PlatformIO will compile them to static libraries and link into executable file.
The source code of each library should be placed in a an own separate directory
("lib/your_library_name/[here are source files]").
For example, see a structure of the following two libraries `Foo` and `Bar`:
|--lib
| |
| |--Bar
| | |--docs
| | |--examples
| | |--src
| | |- Bar.c
| | |- Bar.h
| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html
| |
| |--Foo
| | |- Foo.c
| | |- Foo.h
| |
| |- README --> THIS FILE
|
|- platformio.ini
|--src
|- main.c
and a contents of `src/main.c`:
```
#include <Foo.h>
#include <Bar.h>
int main (void)
{
...
}
```
PlatformIO Library Dependency Finder will find automatically dependent
libraries scanning project source files.
More information about PlatformIO Library Dependency Finder
- https://docs.platformio.org/page/librarymanager/ldf.html

View File

@ -0,0 +1,25 @@
; PlatformIO Project Configuration File
;
; Build options: build flags, source filter
; Upload options: custom upload port, speed and extra flags
; Library options: dependencies, extra library storages
; Advanced options: extra scripting
;
; Please visit documentation for the other options and examples
; https://docs.platformio.org/page/projectconf.html
[env:esp32dev]
platform = espressif32
board = esp32dev
framework = arduino
monitor_speed = 115200
upload_speed = 921600
build_flags =
-DCORE_DEBUG_LEVEL=5
lib_deps = ../../../src
extra_scripts =
pre:run_gen_script.py
board_build.embed_txtfiles =
data/cert/x509_crt_bundle.bin

View File

@ -0,0 +1,12 @@
This is a PlatformIO project that uses a modified WiFiClientSecure library (in `lib`) to
implement proper SSL support using root certificates as discussed
[here](https://github.com/espressif/arduino-esp32/issues/3646#issuecomment-648292677)
It is based on the work by [meltdonw03](https://github.com/meltdown03) in that thread, and the
[BasicHttpsClient example](https://github.com/espressif/arduino-esp32/blob/1.0.4/libraries/HTTPClient/examples/BasicHttpsClient/BasicHttpsClient.ino) from the arduino-esp32 project.
Just copy `include/secrets.hpp.template` to `include/secrets.hpp` and fill in your WiFi details.
Then it should be pretty much ready to go. The local WiFiClientSecure library should take priority.
Debug is set to verbose, so you'll see a lot of noise, but there should also be this readme on success :)
To get a current CA cert bundle download it from [curl's website](https://curl.se/docs/caextract.html).

View File

@ -0,0 +1,6 @@
Import("env")
env.Execute("$PYTHONEXE -m pip install cryptography")
env.Execute("$PYTHONEXE gen_crt_bundle.py --input cacrt_all.pem")
env.Execute("mkdir -p data/cert")
env.Execute("mv -f x509_crt_bundle data/cert/x509_crt_bundle.bin")

View File

@ -0,0 +1,127 @@
/*
* main.cpp
*
* Created on: 15.06.2024
*
*/
#include <Arduino.h>
#include <WiFi.h>
#include <WiFiMulti.h>
#include <WebSocketsClient.h>
extern const uint8_t rootca_crt_bundle_start[] asm(
"_binary_data_cert_x509_crt_bundle_bin_start");
WiFiMulti wifiMulti;
WebSocketsClient webSocket;
#define USE_SERIAL Serial
void setClock() {
configTime(0, 0, "pool.ntp.org", "time.nist.gov");
USE_SERIAL.print(F("Waiting for NTP time sync: "));
time_t nowSecs = time(nullptr);
while(nowSecs < 8 * 3600 * 2) {
delay(500);
USE_SERIAL.print(F("."));
yield();
nowSecs = time(nullptr);
}
USE_SERIAL.println();
struct tm timeinfo;
gmtime_r(&nowSecs, &timeinfo);
USE_SERIAL.print(F("Current time: "));
USE_SERIAL.print(asctime(&timeinfo));
}
void hexdump(const void * mem, uint32_t len, uint8_t cols = 16) {
const uint8_t * src = (const uint8_t *)mem;
USE_SERIAL.printf("\n[HEXDUMP] Address: 0x%08X len: 0x%X (%d)", (ptrdiff_t)src, len, len);
for(uint32_t i = 0; i < len; i++) {
if(i % cols == 0) {
USE_SERIAL.printf("\n[0x%08X] 0x%08X: ", (ptrdiff_t)src, i);
}
USE_SERIAL.printf("%02X ", *src);
src++;
}
USE_SERIAL.printf("\n");
}
void webSocketEvent(WStype_t type, uint8_t * payload, size_t length) {
switch(type) {
case WStype_DISCONNECTED:
USE_SERIAL.printf("[WSc] Disconnected!\n");
break;
case WStype_CONNECTED:
USE_SERIAL.printf("[WSc] Connected to url: %s\n", payload);
// send message to server when Connected
webSocket.sendTXT("Connected");
break;
case WStype_TEXT:
USE_SERIAL.printf("[WSc] get text: %s\n", payload);
// send message to server
// webSocket.sendTXT("message here");
break;
case WStype_BIN:
USE_SERIAL.printf("[WSc] get binary length: %u\n", length);
hexdump(payload, length);
// send data to server
// webSocket.sendBIN(payload, length);
break;
case WStype_ERROR:
case WStype_FRAGMENT_TEXT_START:
case WStype_FRAGMENT_BIN_START:
case WStype_FRAGMENT:
case WStype_FRAGMENT_FIN:
break;
}
}
void setup() {
USE_SERIAL.begin(115200);
USE_SERIAL.setDebugOutput(true);
USE_SERIAL.println();
USE_SERIAL.println();
USE_SERIAL.println();
for(uint8_t t = 4; t > 0; t--) {
USE_SERIAL.printf("[SETUP] BOOT WAIT %d...\n", t);
USE_SERIAL.flush();
delay(1000);
}
wifiMulti.addAP("SSID", "WIFI_PASSPHRASE");
// WiFi.disconnect();
while(wifiMulti.run() != WL_CONNECTED) {
delay(100);
}
setClock();
// server address, port and URL. This server can be flakey.
// Expected response: Request served by 0123456789abcdef
webSocket.beginSslWithBundle("echo.websocket.org", 443, "/", rootca_crt_bundle_start, "");
// event handler
webSocket.onEvent(webSocketEvent);
// use HTTP Basic Authorization this is optional enable if needed
// webSocket.setAuthorization("user", "Password");
// try ever 5000 again if connection has failed
webSocket.setReconnectInterval(5000);
}
void loop() {
webSocket.loop();
}

View File

@ -8,25 +8,29 @@
#include <Arduino.h>
#include <ArduinoJson.h>
#ifdef ESP8266
#if defined(ESP8266)
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266mDNS.h>
#include <Updater.h>
#endif
#ifdef ESP32
#include "WiFi.h"
#include <Updater.h>
#include <Hash.h>
ESP8266WiFiMulti WiFiMulti;
#elif defined(ESP32)
#include <WiFi.h>
#include <WiFiMulti.h>
#include "ESPmDNS.h"
#include <Update.h>
#include <Update.h>
WiFiMulti WiFiMulti;
#else
#error Unsupported device
#endif
#include <WiFiUdp.h>
#include <ESP8266WiFiMulti.h>
#include <WebSocketsClient.h>
#include <Hash.h>
ESP8266WiFiMulti WiFiMulti;
WebSocketsClient webSocket;
#define USE_SERIAL Serial
@ -48,19 +52,12 @@ uint32_t maxSketchSpace = 0;
int SketchSize = 0;
bool ws_conn = false;
String IpAddress2String(const IPAddress& ipAddress)
{
return String(ipAddress[0]) + String(".") +
String(ipAddress[1]) + String(".") +
String(ipAddress[2]) + String(".") +
String(ipAddress[3]);
}
void greetings_(){
StaticJsonDocument<200> doc;
doc["type"] = "greetings";
doc["mac"] = WiFi.macAddress();
doc["ip"] = IpAddress2String(WiFi.localIP());
doc["mac"] = WiFi.macAddress().c_str();
doc["ip"] = WiFi.localIP().toString().c_str();
doc["version"] = version;
doc["name"] = name;
doc["chip"] = chip;
@ -73,7 +70,7 @@ void greetings_(){
void register_(){
StaticJsonDocument<200> doc;
doc["type"] = "register";
doc["mac"] = WiFi.macAddress();
doc["mac"] = WiFi.macAddress().c_str();
char data[200];
serializeJson(doc, data);
@ -88,11 +85,10 @@ typedef struct {
CALLBACK_FUNCTION func;
} RESPONSES_STRUCT;
void OTA(JsonDocument &msg){
void OTA_RESPONSES(JsonDocument &msg){
USE_SERIAL.print(F("[WSc] OTA mode: "));
const char* go = "go";
const char* ok = "ok";
if(strncmp( msg["value"], go, strlen(go)) == 0 ) {
String val = msg["value"];
if(val == "go") {
USE_SERIAL.print(F("go\n"));
SketchSize = int(msg["size"]);
maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000;
@ -103,27 +99,31 @@ void OTA(JsonDocument &msg){
Update.printError(Serial);
ESP.restart();
}
} else if (strncmp( msg["value"], ok, strlen(ok)) == 0) {
} else if (val == "ok") {
USE_SERIAL.print(F("OK\n"));
register_();
} else {
USE_SERIAL.print(F("unknown value : "));
USE_SERIAL.print(msg["value"].as<char>());
USE_SERIAL.print(val);
USE_SERIAL.print(F("\n"));
}
}
void STATE(JsonDocument &msg){
void STA_RESPONSES(JsonDocument &msg){
// Do something with message
}
RESPONSES_STRUCT responses[] = {
{"ota", OTA},
{"state", STATE},
// Count of responses handled by RESPONSES_STRUCT
// increase increase if another response handler is added
const int nrOfResponses = 2;
RESPONSES_STRUCT responses[nrOfResponses] = {
{"ota", OTA_RESPONSES},
{"state", STA_RESPONSES},
};
void text(uint8_t * payload, size_t length){
// Convert mesage to something usable
// Convert message to something usable
char msgch[length];
for (unsigned int i = 0; i < length; i++)
{
@ -145,9 +145,10 @@ void text(uint8_t * payload, size_t length){
// Handle each TYPE of message
int b = 0;
for( b=0 ; strlen(responses[b].type) ; b++ )
String t = doc_in["type"];
for( b=0 ; b<nrOfResponses ; b++ )
{
if( strncmp(doc_in["type"], responses[b].type, strlen(responses[b].type)) == 0 ) {
if(t == responses[b].type) {
responses[b].func(doc_in);
}
}

View File

@ -55,7 +55,7 @@ async def binary_send(websocket, fw_file):
with open(fw_file, "rb") as binaryfile:
while True:
chunk = binaryfile.read(2048)
chunk = binaryfile.read(4096)
if not chunk:
break
try:
@ -63,7 +63,7 @@ async def binary_send(websocket, fw_file):
except Exception as exception:
Logger.exception(exception)
return False
time.sleep(0.2)
asyncio.sleep(0.2)
def version_checker(name, vdev, vapp):
@ -79,7 +79,7 @@ def version_checker(name, vdev, vapp):
class WsOtaHandler (threading.Thread):
"""Thread handling ota update
Runing ota directly from message would kill WS
Running ota directly from message would kill WS
as message bus would timeout.
"""
def __init__(self, name, message, websocket):
@ -90,7 +90,7 @@ class WsOtaHandler (threading.Thread):
def run(self, ):
try:
asyncio.run(self.start_)
asyncio.run(self.start_())
except Exception as exception:
Logger.exception(exception)
finally:
@ -163,7 +163,7 @@ async def _register(websocket, message):
Logger.info("Client(%s) mac: %s", name, mac)
# Some code
response = {'response_type': 'registry', 'state': 'ok'}
response = {'type': 'registry', 'state': 'ok'}
await websocket.send(json.dumps(response))
@ -173,13 +173,13 @@ async def _state(websocket, message):
Logger.info("Client(%s) mac: %s", name, mac)
# Some code
response = {'response_type': 'state', 'state': 'ok'}
response = {'type': 'state', 'state': 'ok'}
await websocket.send(json.dumps(response))
async def _unhandleld(websocket, msg):
async def _unhandled(websocket, msg):
Logger.info("Unhandled message from device: %s", str(msg))
response = {'response_type': 'response', 'state': 'nok'}
response = {'type': 'response', 'state': 'nok'}
await websocket.send(json.dumps(response))
@ -206,7 +206,7 @@ async def message_received(websocket, message) -> None:
type_ = msg_json.get('type')
name = msg_json.get('name')
func = switcher.get(type_, _unhandleld)
func = switcher.get(type_, _unhandled)
Logger.debug("Client(%s)said: %s", name, type_)
try:
@ -225,7 +225,7 @@ async def ws_server(websocket, path) -> None:
async def main():
"""Server starter
Normal user can bind only port nubers greater than 1024
Normal user can bind only port numbers greater than 1024
"""
async with websockets.serve(ws_server, "10.0.1.5", 8081):
await asyncio.Future() # run forever

View File

@ -16,10 +16,10 @@
"keywords": "wifi, http, web, server, client, websocket",
"license": "LGPL-2.1",
"name": "WebSockets",
"platforms": "atmelavr, espressif8266, espressif32",
"platforms": "atmelavr, espressif8266, espressif32, raspberrypi",
"repository": {
"type": "git",
"url": "https://github.com/Links2004/arduinoWebSockets.git"
},
"version": "2.3.7"
"version": "2.4.1"
}

View File

@ -1,5 +1,5 @@
name=WebSockets
version=2.3.7
version=2.4.1
author=Markus Sattler
maintainer=Markus Sattler
sentence=WebSockets for Arduino (Server + Client)

View File

@ -15,39 +15,39 @@ SocketIOclient::SocketIOclient() {
SocketIOclient::~SocketIOclient() {
}
void SocketIOclient::begin(const char * host, uint16_t port, const char * url, const char * protocol) {
void SocketIOclient::begin(const char * host, uint16_t port, const char * url, const char * protocol, uint32_t pingInterval, uint32_t pongTimeout, uint8_t disconnectTimeoutCount) {
WebSocketsClient::beginSocketIO(host, port, url, protocol);
WebSocketsClient::enableHeartbeat(60 * 1000, 90 * 1000, 5);
WebSocketsClient::enableHeartbeat(pingInterval, pongTimeout, disconnectTimeoutCount);
initClient();
}
void SocketIOclient::begin(String host, uint16_t port, String url, String protocol) {
void SocketIOclient::begin(String host, uint16_t port, String url, String protocol, uint32_t pingInterval, uint32_t pongTimeout, uint8_t disconnectTimeoutCount) {
WebSocketsClient::beginSocketIO(host, port, url, protocol);
WebSocketsClient::enableHeartbeat(60 * 1000, 90 * 1000, 5);
WebSocketsClient::enableHeartbeat(pingInterval, pongTimeout, disconnectTimeoutCount);
initClient();
}
#if defined(HAS_SSL)
void SocketIOclient::beginSSL(const char * host, uint16_t port, const char * url, const char * protocol) {
void SocketIOclient::beginSSL(const char * host, uint16_t port, const char * url, const char * protocol, uint32_t pingInterval, uint32_t pongTimeout, uint8_t disconnectTimeoutCount) {
WebSocketsClient::beginSocketIOSSL(host, port, url, protocol);
WebSocketsClient::enableHeartbeat(60 * 1000, 90 * 1000, 5);
WebSocketsClient::enableHeartbeat(pingInterval, pongTimeout, disconnectTimeoutCount);
initClient();
}
void SocketIOclient::beginSSL(String host, uint16_t port, String url, String protocol) {
void SocketIOclient::beginSSL(String host, uint16_t port, String url, String protocol, uint32_t pingInterval, uint32_t pongTimeout, uint8_t disconnectTimeoutCount) {
WebSocketsClient::beginSocketIOSSL(host, port, url, protocol);
WebSocketsClient::enableHeartbeat(60 * 1000, 90 * 1000, 5);
WebSocketsClient::enableHeartbeat(pingInterval, pongTimeout, disconnectTimeoutCount);
initClient();
}
#if defined(SSL_BARESSL)
void SocketIOclient::beginSSLWithCA(const char * host, uint16_t port, const char * url, const char * CA_cert, const char * protocol) {
void SocketIOclient::beginSSLWithCA(const char * host, uint16_t port, const char * url, const char * CA_cert, const char * protocol, uint32_t pingInterval, uint32_t pongTimeout, uint8_t disconnectTimeoutCount) {
WebSocketsClient::beginSocketIOSSLWithCA(host, port, url, CA_cert, protocol);
WebSocketsClient::enableHeartbeat(60 * 1000, 90 * 1000, 5);
WebSocketsClient::enableHeartbeat(pingInterval, pongTimeout, disconnectTimeoutCount);
initClient();
}
void SocketIOclient::beginSSLWithCA(const char * host, uint16_t port, const char * url, BearSSL::X509List * CA_cert, const char * protocol) {
void SocketIOclient::beginSSLWithCA(const char * host, uint16_t port, const char * url, BearSSL::X509List * CA_cert, const char * protocol, uint32_t pingInterval, uint32_t pongTimeout, uint8_t disconnectTimeoutCount) {
WebSocketsClient::beginSocketIOSSLWithCA(host, port, url, CA_cert, protocol);
WebSocketsClient::enableHeartbeat(60 * 1000, 90 * 1000, 5);
WebSocketsClient::enableHeartbeat(pingInterval, pongTimeout, disconnectTimeoutCount);
initClient();
}
@ -93,6 +93,10 @@ void SocketIOclient::setReconnectInterval(unsigned long time) {
return WebSocketsClient::setReconnectInterval(time);
}
void SocketIOclient::disconnect(void) {
WebSocketsClient::disconnect();
}
/**
* send text data to client
* @param num uint8_t client id

View File

@ -47,15 +47,15 @@ class SocketIOclient : protected WebSocketsClient {
SocketIOclient(void);
virtual ~SocketIOclient(void);
void begin(const char * host, uint16_t port, const char * url = "/socket.io/?EIO=3", const char * protocol = "arduino");
void begin(String host, uint16_t port, String url = "/socket.io/?EIO=3", String protocol = "arduino");
void begin(const char * host, uint16_t port, const char * url = "/socket.io/?EIO=3", const char * protocol = "arduino", uint32_t pingInterval = 60 * 1000, uint32_t pongTimeout = 90 * 1000, uint8_t disconnectTimeoutCount = 5);
void begin(String host, uint16_t port, String url = "/socket.io/?EIO=3", String protocol = "arduino", uint32_t pingInterval = 60 * 1000, uint32_t pongTimeout = 90 * 1000, uint8_t disconnectTimeoutCount = 5);
#ifdef HAS_SSL
void beginSSL(const char * host, uint16_t port, const char * url = "/socket.io/?EIO=3", const char * protocol = "arduino");
void beginSSL(String host, uint16_t port, String url = "/socket.io/?EIO=3", String protocol = "arduino");
void beginSSL(const char * host, uint16_t port, const char * url = "/socket.io/?EIO=3", const char * protocol = "arduino", uint32_t pingInterval = 60 * 1000, uint32_t pongTimeout = 90 * 1000, uint8_t disconnectTimeoutCount = 5);
void beginSSL(String host, uint16_t port, String url = "/socket.io/?EIO=3", String protocol = "arduino", uint32_t pingInterval = 60 * 1000, uint32_t pongTimeout = 90 * 1000, uint8_t disconnectTimeoutCount = 5);
#ifndef SSL_AXTLS
void beginSSLWithCA(const char * host, uint16_t port, const char * url = "/socket.io/?EIO=3", const char * CA_cert = NULL, const char * protocol = "arduino");
void beginSSLWithCA(const char * host, uint16_t port, const char * url = "/socket.io/?EIO=3", BearSSL::X509List * CA_cert = NULL, const char * protocol = "arduino");
void beginSSLWithCA(const char * host, uint16_t port, const char * url = "/socket.io/?EIO=3", const char * CA_cert = NULL, const char * protocol = "arduino", uint32_t pingInterval = 60 * 1000, uint32_t pongTimeout = 90 * 1000, uint8_t disconnectTimeoutCount = 5);
void beginSSLWithCA(const char * host, uint16_t port, const char * url = "/socket.io/?EIO=3", BearSSL::X509List * CA_cert = NULL, const char * protocol = "arduino", uint32_t pingInterval = 60 * 1000, uint32_t pongTimeout = 90 * 1000, uint8_t disconnectTimeoutCount = 5);
void setSSLClientCertKey(const char * clientCert = NULL, const char * clientPrivateKey = NULL);
void setSSLClientCertKey(BearSSL::X509List * clientCert = NULL, BearSSL::PrivateKey * clientPrivateKey = NULL);
#endif
@ -63,6 +63,7 @@ class SocketIOclient : protected WebSocketsClient {
bool isConnected(void);
void onEvent(SocketIOclientEvent cbEvent);
void disconnect(void);
bool sendEVENT(uint8_t * payload, size_t length = 0, bool headerToPayload = false);
bool sendEVENT(const uint8_t * payload, size_t length = 0);

View File

@ -482,7 +482,7 @@ void WebSockets::handleWebsocketPayloadCb(WSclient_t * client, bool ok, uint8_t
switch(header->opCode) {
case WSop_text:
DEBUG_WEBSOCKETS("[WS][%d][handleWebsocket] text: %s\n", client->num, payload);
// no break here!
// fallthrough
case WSop_binary:
case WSop_continuation:
messageReceived(client, header->opCode, payload, header->payloadLen, header->fin);
@ -571,6 +571,7 @@ String WebSockets::acceptKey(String & clientKey) {
*/
String WebSockets::base64_encode(uint8_t * data, size_t length) {
size_t size = ((length * 1.6f) + 1);
size = std::max(size, (size_t)5); // minimum buffer size
char * buffer = (char *)malloc(size);
if(buffer) {
base64_encodestate _state;
@ -749,7 +750,7 @@ void WebSockets::handleHBTimeout(WSclient_t * client) {
client->pongTimeoutCount++;
client->lastPing = millis() - client->pingInterval - 500; // force ping on the next run
DEBUG_WEBSOCKETS("[HBtimeout] pong TIMEOUT! lp=%d millis=%d pi=%d count=%d\n", client->lastPing, millis(), pi, client->pongTimeoutCount);
DEBUG_WEBSOCKETS("[HBtimeout] pong TIMEOUT! lp=%d millis=%lu pi=%d count=%d\n", client->lastPing, millis(), pi, client->pongTimeoutCount);
if(client->disconnectTimeoutCount && client->pongTimeoutCount >= client->disconnectTimeoutCount) {
DEBUG_WEBSOCKETS("[HBtimeout] count=%d, DISCONNECTING\n", client->pongTimeoutCount);

View File

@ -50,7 +50,7 @@
DEBUG_ESP_PORT.flush(); \
}
#else
//#define DEBUG_WEBSOCKETS(...) os_printf( __VA_ARGS__ )
// #define DEBUG_WEBSOCKETS(...) os_printf( __VA_ARGS__ )
#endif
#endif
@ -67,7 +67,7 @@
#define WEBSOCKETS_USE_BIG_MEM
#define GET_FREE_HEAP ESP.getFreeHeap()
// moves all Header strings to Flash (~300 Byte)
//#define WEBSOCKETS_SAVE_RAM
// #define WEBSOCKETS_SAVE_RAM
#if defined(ESP8266)
#define WEBSOCKETS_YIELD() delay(0)
@ -84,6 +84,15 @@
#define GET_FREE_HEAP System.freeMemory()
#define WEBSOCKETS_YIELD()
#define WEBSOCKETS_YIELD_MORE()
#elif defined(ARDUINO_ARCH_RP2040)
#define WEBSOCKETS_MAX_DATA_SIZE (15 * 1024)
#define WEBSOCKETS_USE_BIG_MEM
#define GET_FREE_HEAP rp2040.getFreeHeap()
#define WEBSOCKETS_YIELD() yield()
#define WEBSOCKETS_YIELD_MORE() delay(1)
#else
// atmega328p has only 2KB ram!
@ -94,7 +103,9 @@
#define WEBSOCKETS_YIELD_MORE()
#endif
#ifndef WEBSOCKETS_TCP_TIMEOUT
#define WEBSOCKETS_TCP_TIMEOUT (5000)
#endif
#define NETWORK_ESP8266_ASYNC (0)
#define NETWORK_ESP8266 (1)
@ -102,6 +113,7 @@
#define NETWORK_ENC28J60 (3)
#define NETWORK_ESP32 (4)
#define NETWORK_ESP32_ETH (5)
#define NETWORK_RP2040 (6)
// max size of the WS Message Header
#define WEBSOCKETS_MAX_HEADER_SIZE (14)
@ -110,12 +122,16 @@
// select Network type based
#if defined(ESP8266) || defined(ESP31B)
#define WEBSOCKETS_NETWORK_TYPE NETWORK_ESP8266
//#define WEBSOCKETS_NETWORK_TYPE NETWORK_ESP8266_ASYNC
//#define WEBSOCKETS_NETWORK_TYPE NETWORK_W5100
// #define WEBSOCKETS_NETWORK_TYPE NETWORK_ESP8266_ASYNC
// #define WEBSOCKETS_NETWORK_TYPE NETWORK_W5100
#elif defined(ESP32)
#define WEBSOCKETS_NETWORK_TYPE NETWORK_ESP32
//#define WEBSOCKETS_NETWORK_TYPE NETWORK_ESP32_ETH
// #define WEBSOCKETS_NETWORK_TYPE NETWORK_ESP32_ETH
#elif defined(ARDUINO_ARCH_RP2040)
#define WEBSOCKETS_NETWORK_TYPE NETWORK_RP2040
#else
#define WEBSOCKETS_NETWORK_TYPE NETWORK_W5100
@ -199,6 +215,15 @@
#define WEBSOCKETS_NETWORK_CLASS WiFiClient
#define WEBSOCKETS_NETWORK_SERVER_CLASS WiFiServer
#elif(WEBSOCKETS_NETWORK_TYPE == NETWORK_RP2040)
#include <WiFi.h>
#include <WiFiClientSecure.h>
#define SSL_BARESSL
#define WEBSOCKETS_NETWORK_CLASS WiFiClient
#define WEBSOCKETS_NETWORK_SSL_CLASS WiFiClientSecure
#define WEBSOCKETS_NETWORK_SERVER_CLASS WiFiServer
#else
#error "no network type selected!"
#endif

View File

@ -28,23 +28,29 @@
#include <WebSocketsServer.h>
#include <ESP8266WebServer.h>
#if WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266 && WEBSERVER_HAS_HOOK
#if((WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266) || (WEBSOCKETS_NETWORK_TYPE == NETWORK_RP2040)) && WEBSERVER_HAS_HOOK
class WebSockets4WebServer : public WebSocketsServerCore {
#if defined(ESP8266)
using WebServerClass = ESP8266WebServer;
#else
using WebServerClass = WebServer;
#endif
public:
WebSockets4WebServer(const String & origin = "", const String & protocol = "arduino")
: WebSocketsServerCore(origin, protocol) {
begin();
}
ESP8266WebServer::HookFunction hookForWebserver(const String & wsRootDir, WebSocketServerEvent event) {
WebServerClass::HookFunction hookForWebserver(const String & wsRootDir, WebSocketServerEvent event) {
onEvent(event);
return [&, wsRootDir](const String & method, const String & url, WiFiClient * tcpClient, ESP8266WebServer::ContentTypeFunction contentType) {
return [&, wsRootDir](const String & method, const String & url, WiFiClient * tcpClient, WebServerClass::ContentTypeFunction contentType) {
(void)contentType;
if(!(method == "GET" && url.indexOf(wsRootDir) == 0)) {
return ESP8266WebServer::CLIENT_REQUEST_CAN_CONTINUE;
return WebServerClass::CLIENT_REQUEST_CAN_CONTINUE;
}
// allocate a WiFiClient copy (like in WebSocketsServer::handleNewClients())
@ -63,7 +69,7 @@ class WebSockets4WebServer : public WebSocketsServerCore {
}
// tell webserver to not close but forget about this client
return ESP8266WebServer::CLIENT_IS_GIVEN;
return WebServerClass::CLIENT_IS_GIVEN;
};
}
};

View File

@ -48,6 +48,9 @@ void WebSocketsClient::begin(const char * host, uint16_t port, const char * url,
#if defined(HAS_SSL)
_fingerprint = SSL_FINGERPRINT_NULL;
_CA_cert = NULL;
#ifdef ESP32
_CA_bundle = NULL;
#endif
#endif
_client.num = 0;
@ -76,6 +79,8 @@ void WebSocketsClient::begin(const char * host, uint16_t port, const char * url,
#ifdef ESP8266
randomSeed(RANDOM_REG32);
#elif defined(ARDUINO_ARCH_RP2040)
randomSeed(rp2040.hwrand32());
#else
// todo find better seed
randomSeed(millis());
@ -105,6 +110,7 @@ void WebSocketsClient::beginSSL(const char * host, uint16_t port, const char * u
_client.isSSL = true;
_fingerprint = fingerprint;
_CA_cert = NULL;
_CA_bundle = NULL;
}
void WebSocketsClient::beginSSL(String host, uint16_t port, String url, String fingerprint, String protocol) {
@ -116,7 +122,16 @@ void WebSocketsClient::beginSslWithCA(const char * host, uint16_t port, const ch
_client.isSSL = true;
_fingerprint = SSL_FINGERPRINT_NULL;
_CA_cert = CA_cert;
_CA_bundle = NULL;
}
void WebSocketsClient::beginSslWithBundle(const char * host, uint16_t port, const char * url, const uint8_t * CA_bundle, const char * protocol) {
begin(host, port, url, protocol);
_client.isSSL = true;
_fingerprint = SSL_FINGERPRINT_NULL;
_CA_cert = NULL;
_CA_bundle = CA_bundle;
}
#else
void WebSocketsClient::beginSSL(const char * host, uint16_t port, const char * url, const uint8_t * fingerprint, const char * protocol) {
begin(host, port, url, protocol);
@ -224,11 +239,16 @@ void WebSocketsClient::loop(void) {
_client.ssl->setCACert(_CA_cert);
#elif defined(ESP8266) && defined(SSL_AXTLS)
_client.ssl->setCACert((const uint8_t *)_CA_cert, strlen(_CA_cert) + 1);
#elif defined(ESP8266) && defined(SSL_BARESSL)
#elif(defined(ESP8266) || defined(ARDUINO_ARCH_RP2040)) && defined(SSL_BARESSL)
_client.ssl->setTrustAnchors(_CA_cert);
#else
#error setCACert not implemented
#endif
#if defined(ESP32)
} else if(_CA_bundle) {
DEBUG_WEBSOCKETS("[WS-Client] setting CA bundle");
_client.ssl->setCACertBundle(_CA_bundle);
#endif
#if defined(ESP32)
} else if(!SSL_FINGERPRINT_IS_SET) {
_client.ssl->setInsecure();
@ -426,9 +446,9 @@ bool WebSocketsClient::isConnected(void) {
return (_client.status == WSC_CONNECTED);
}
//#################################################################################
//#################################################################################
//#################################################################################
// #################################################################################
// #################################################################################
// #################################################################################
/**
*
@ -473,7 +493,7 @@ void WebSocketsClient::messageReceived(WSclient_t * client, WSopcode_t opcode, u
void WebSocketsClient::clientDisconnect(WSclient_t * client) {
bool event = false;
#if(WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266) || (WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP32)
#if(WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266) || (WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP32) || (WEBSOCKETS_NETWORK_TYPE == NETWORK_RP2040)
if(client->isSSL && client->ssl) {
if(client->ssl->connected()) {
client->ssl->flush();
@ -733,7 +753,7 @@ void WebSocketsClient::handleHeader(WSclient_t * client, String * headerLine) {
client->cExtensions = headerValue;
} else if(headerName.equalsIgnoreCase(WEBSOCKETS_STRING("Sec-WebSocket-Version"))) {
client->cVersion = headerValue.toInt();
} else if(headerName.equalsIgnoreCase(WEBSOCKETS_STRING("Set-Cookie"))) {
} else if(headerName.equalsIgnoreCase(WEBSOCKETS_STRING("Set-Cookie")) && headerValue.indexOf(" io=") > -1) {
if(headerValue.indexOf(';') > -1) {
client->cSessionId = headerValue.substring(headerValue.indexOf('=') + 1, headerValue.indexOf(";"));
} else {
@ -864,7 +884,7 @@ void WebSocketsClient::connectedCb() {
_client.tcp->setTimeout(WEBSOCKETS_TCP_TIMEOUT);
#endif
#if(WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266) || (WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP32)
#if(WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266) || (WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP32) || (WEBSOCKETS_NETWORK_TYPE == NETWORK_RP2040)
_client.tcp->setNoDelay(true);
#endif

View File

@ -53,6 +53,9 @@ class WebSocketsClient : protected WebSockets {
void setSSLClientCertKey(const char * clientCert = NULL, const char * clientPrivateKey = NULL);
#endif
void beginSslWithCA(const char * host, uint16_t port, const char * url = "/", const char * CA_cert = NULL, const char * protocol = "arduino");
#ifdef ESP32
void beginSslWithBundle(const char * host, uint16_t port, const char * url = "/", const uint8_t * CA_bundle = NULL, const char * protocol = "arduino");
#endif
#endif
void beginSocketIO(const char * host, uint16_t port, const char * url = "/socket.io/?EIO=3", const char * protocol = "arduino");
@ -112,6 +115,7 @@ class WebSocketsClient : protected WebSockets {
#ifdef SSL_AXTLS
String _fingerprint;
const char * _CA_cert;
const uint8_t * _CA_bundle;
#define SSL_FINGERPRINT_IS_SET (_fingerprint.length())
#define SSL_FINGERPRINT_NULL ""
#else

View File

@ -65,6 +65,7 @@ WebSocketsServerCore::~WebSocketsServerCore() {
}
WebSocketsServer::~WebSocketsServer() {
delete _server;
}
/**
@ -85,6 +86,8 @@ void WebSocketsServerCore::begin(void) {
#elif defined(ESP32)
#define DR_REG_RNG_BASE 0x3ff75144
randomSeed(READ_PERI_REG(DR_REG_RNG_BASE));
#elif defined(ARDUINO_ARCH_RP2040)
randomSeed(rp2040.hwrand32());
#else
// TODO find better seed
randomSeed(millis());
@ -394,7 +397,7 @@ bool WebSocketsServerCore::clientIsConnected(uint8_t num) {
return clientIsConnected(client);
}
#if(WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266) || (WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266_ASYNC) || (WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP32)
#if(WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266) || (WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266_ASYNC) || (WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP32) || (WEBSOCKETS_NETWORK_TYPE == NETWORK_RP2040)
/**
* get an IP for a client
* @param num uint8_t client id
@ -412,9 +415,9 @@ IPAddress WebSocketsServerCore::remoteIP(uint8_t num) {
}
#endif
//#################################################################################
//#################################################################################
//#################################################################################
// #################################################################################
// #################################################################################
// #################################################################################
/**
* handle new client connection
@ -426,8 +429,16 @@ WSclient_t * WebSocketsServerCore::newClient(WEBSOCKETS_NETWORK_CLASS * TCPclien
for(uint8_t i = 0; i < WEBSOCKETS_SERVER_CLIENT_MAX; i++) {
client = &_clients[i];
// state is not connected or tcp connection is lost
if(!clientIsConnected(client)) {
// look for match to existing socket before creating a new one
if(clientIsConnected(client)) {
#if(WEBSOCKETS_NETWORK_TYPE == NETWORK_W5100)
// Check to see if it is the same socket - if so, return it
if(client->tcp->getSocketNumber() == TCPclient->getSocketNumber()) {
return client;
}
#endif
} else {
// state is not connected or tcp connection is lost
client->tcp = TCPclient;
#if(WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266) || (WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP32)
@ -439,7 +450,7 @@ WSclient_t * WebSocketsServerCore::newClient(WEBSOCKETS_NETWORK_CLASS * TCPclien
client->tcp->setTimeout(WEBSOCKETS_TCP_TIMEOUT);
#endif
client->status = WSC_HEADER;
#if(WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266) || (WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266_ASYNC) || (WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP32)
#if(WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266) || (WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266_ASYNC) || (WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP32) || (WEBSOCKETS_NETWORK_TYPE == NETWORK_RP2040)
#ifndef NODEBUG_WEBSOCKETS
IPAddress ip = client->tcp->remoteIP();
#endif
@ -521,7 +532,7 @@ void WebSocketsServerCore::dropNativeClient(WSclient_t * client) {
}
if(client->tcp) {
if(client->tcp->connected()) {
#if(WEBSOCKETS_NETWORK_TYPE != NETWORK_ESP8266_ASYNC) && (WEBSOCKETS_NETWORK_TYPE != NETWORK_ESP32)
#if(WEBSOCKETS_NETWORK_TYPE != NETWORK_ESP8266_ASYNC) && (WEBSOCKETS_NETWORK_TYPE != NETWORK_ESP32) && (WEBSOCKETS_NETWORK_TYPE != NETWORK_RP2040)
client->tcp->flush();
#endif
client->tcp->stop();
@ -540,7 +551,7 @@ void WebSocketsServerCore::dropNativeClient(WSclient_t * client) {
* @param client WSclient_t * ptr to the client struct
*/
void WebSocketsServerCore::clientDisconnect(WSclient_t * client) {
#if(WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266) || (WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP32)
#if(WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266) || (WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP32) || (WEBSOCKETS_NETWORK_TYPE == NETWORK_RP2040)
if(client->isSSL && client->ssl) {
if(client->ssl->connected()) {
client->ssl->flush();
@ -614,7 +625,7 @@ WSclient_t * WebSocketsServerCore::handleNewClient(WEBSOCKETS_NETWORK_CLASS * tc
if(!client) {
// no free space to handle client
#if(WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266) || (WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP32)
#if(WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266) || (WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP32) || (WEBSOCKETS_NETWORK_TYPE == NETWORK_RP2040)
#ifndef NODEBUG_WEBSOCKETS
IPAddress ip = tcpClient->remoteIP();
#endif
@ -627,6 +638,7 @@ WSclient_t * WebSocketsServerCore::handleNewClient(WEBSOCKETS_NETWORK_CLASS * tc
client = &dummy;
client->tcp = tcpClient;
dropNativeClient(client);
return nullptr;
}
WEBSOCKETS_YIELD();
@ -638,12 +650,12 @@ WSclient_t * WebSocketsServerCore::handleNewClient(WEBSOCKETS_NETWORK_CLASS * tc
* Handle incoming Connection Request
*/
void WebSocketsServer::handleNewClients(void) {
#if(WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266) || (WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP32)
#if(WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266) || (WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP32) || (WEBSOCKETS_NETWORK_TYPE == NETWORK_RP2040)
while(_server->hasClient()) {
#endif
// store new connection
WEBSOCKETS_NETWORK_CLASS * tcpClient = new WEBSOCKETS_NETWORK_CLASS(_server->available());
WEBSOCKETS_NETWORK_CLASS * tcpClient = new WEBSOCKETS_NETWORK_CLASS(_server->accept());
if(!tcpClient) {
DEBUG_WEBSOCKETS("[WS-Client] creating Network class failed!");
return;
@ -651,7 +663,7 @@ void WebSocketsServer::handleNewClients(void) {
handleNewClient(tcpClient);
#if(WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266) || (WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP32)
#if(WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266) || (WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP32) || (WEBSOCKETS_NETWORK_TYPE == NETWORK_RP2040)
}
#endif
}
@ -922,7 +934,7 @@ void WebSocketsServer::begin(void) {
void WebSocketsServer::close(void) {
WebSocketsServerCore::close();
#if(WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266)
#if(WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266) || (WEBSOCKETS_NETWORK_TYPE == NETWORK_RP2040)
_server->close();
#elif(WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP32) || (WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266_ASYNC)
_server->end();

View File

@ -90,7 +90,7 @@ class WebSocketsServerCore : protected WebSockets {
void enableHeartbeat(uint32_t pingInterval, uint32_t pongTimeout, uint8_t disconnectTimeoutCount);
void disableHeartbeat();
#if(WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266) || (WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266_ASYNC) || (WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP32)
#if(WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266) || (WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266_ASYNC) || (WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP32) || (WEBSOCKETS_NETWORK_TYPE == NETWORK_RP2040)
IPAddress remoteIP(uint8_t num);
#endif

View File

@ -1,6 +1,6 @@
/**
* @file WebSocketsVersion.h
* @date 05.04.2022
* @date 01.05.2023
* @author Markus Sattler
*
* Copyright (c) 2015 Markus Sattler. All rights reserved.
@ -25,12 +25,12 @@
#ifndef WEBSOCKETSVERSION_H_
#define WEBSOCKETSVERSION_H_
#define WEBSOCKETS_VERSION "2.3.7"
#define WEBSOCKETS_VERSION "2.4.1"
#define WEBSOCKETS_VERSION_MAJOR 2
#define WEBSOCKETS_VERSION_MINOR 3
#define WEBSOCKETS_VERSION_PATCH 7
#define WEBSOCKETS_VERSION_MINOR 4
#define WEBSOCKETS_VERSION_PATCH 1
#define WEBSOCKETS_VERSION_INT 2003007
#define WEBSOCKETS_VERSION_INT 2004001
#endif /* WEBSOCKETSVERSION_H_ */

View File

@ -9,7 +9,7 @@ For details, see http://sourceforge.net/projects/libb64
#include <core_esp8266_features.h>
#endif
#if defined(ESP32)
#if defined(ESP32) || defined(ARDUINO_ARCH_RP2040)
#define CORE_HAS_LIBB64
#endif

View File

@ -9,7 +9,7 @@ For details, see http://sourceforge.net/projects/libb64
#include <core_esp8266_features.h>
#endif
#if defined(ESP32)
#if defined(ESP32) || defined(ARDUINO_ARCH_RP2040)
#define CORE_HAS_LIBB64
#endif

View File

@ -29,6 +29,23 @@ function build_sketches()
done
}
function build_sketch_cli()
{
local sketch=$1
local board=$2
arduino-cli --log --log-level info compile -b "$board" "$sketch"
result=$?
if [ $result -ne 0 ]; then
echo "Build failed ($sketch) build verbose..."
arduino-cli --log --log-level debug compile -b "$board" "$sketch"
result=$?
fi
if [ $result -ne 0 ]; then
echo "Build failed ($1) $sketch"
return $result
fi
}
function build_sketch()
{
local arduino=$1
@ -72,7 +89,7 @@ function get_sketches_json_matrix()
local arduino=$1
local srcpath=$2
local platform=$3
local ideversion=$4
local cliversion=$4
local board=$5
local sketches=($(find $srcpath -name *.ino))
for sketch in "${sketches[@]}" ; do
@ -81,18 +98,27 @@ function get_sketches_json_matrix()
if [[ -f "$sketchdir/.$platform.skip" ]]; then
continue
fi
echo -en "{\"name\":\"$sketchname\",\"board\":\"$board\",\"ideversion\":\"$ideversion\",\"cpu\":\"$platform\",\"sketch\":\"$sketch\"}"
echo -en "{\"name\":\"$sketchname\",\"board\":\"$board\",\"cliversion\":\"$cliversion\",\"cpu\":\"$platform\",\"sketch\":\"$sketch\"}"
if [[ $sketch != ${sketches[-1]} ]] ; then
echo -en ","
fi
done
}
function get_core_cli() {
export ARDUINO_BOARD_MANAGER_ADDITIONAL_URLS="https://arduino.esp8266.com/stable/package_esp8266com_index.json https://espressif.github.io/arduino-esp32/package_esp32_index.json https://github.com/earlephilhower/arduino-pico/releases/download/global/package_rp2040_index.json"
arduino-cli core update-index
arduino-cli core install esp8266:esp8266
arduino-cli core install esp32:esp32
arduino-cli core install arduino:mbed_rp2040
}
function get_core()
{
echo Setup core for $1
cd $HOME/arduino_ide/hardware
mkdir -p $HOME/arduino_ide/packages/hardware
cd $HOME/arduino_ide/packages/hardware
if [ "$1" = "esp8266" ] ; then
mkdir esp8266com