Skip to content

Commit 50dac00

Browse files
committed
Improve SD debug demo and add new BLE demo.
1 parent c4b2e9b commit 50dac00

File tree

2 files changed

+292
-4
lines changed

2 files changed

+292
-4
lines changed

websocket/debug_ble.h

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
#include <Arduino.h>
2+
#include <BLEDevice.h>
3+
#include <BLEUtils.h>
4+
#include <BLEServer.h>
5+
6+
// Define BLE UUIDs
7+
#define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
8+
#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"
9+
10+
BLEServer* pServer = NULL;
11+
BLECharacteristic* pCharacteristic = NULL;
12+
bool deviceConnected = false;
13+
14+
// Callback class for connection events
15+
class MyServerCallbacks : public BLEServerCallbacks {
16+
void onConnect(BLEServer* pServer) {
17+
deviceConnected = true;
18+
Serial.println("Device connected");
19+
}
20+
21+
void onDisconnect(BLEServer* pServer) {
22+
deviceConnected = false;
23+
Serial.println("Device disconnected");
24+
// Restart advertising so the client can reconnect:
25+
pServer->startAdvertising();
26+
}
27+
};
28+
29+
// Callback class for characteristic events
30+
class MyCallbacks : public BLECharacteristicCallbacks {
31+
void onWrite(BLECharacteristic* pCharacteristic) {
32+
std::string rxData = pCharacteristic->getValue();
33+
if (rxData.length() > 0) {
34+
// Convert std::string to String
35+
String receivedData = String(rxData.c_str());
36+
37+
// Print the received file name
38+
Serial.print("Received file name: ");
39+
Serial.println(receivedData);
40+
}
41+
}
42+
};
43+
44+
void setup() {
45+
Serial.begin(115200);
46+
delay(1000);
47+
48+
// Initialize BLE
49+
BLEDevice::init("ESP32-S3 BLE Demo");
50+
pServer = BLEDevice::createServer();
51+
pServer->setCallbacks(new MyServerCallbacks());
52+
53+
// Create BLE Service
54+
BLEService* pService = pServer->createService(SERVICE_UUID);
55+
56+
// Create a BLE Characteristic
57+
pCharacteristic = pService->createCharacteristic(
58+
CHARACTERISTIC_UUID,
59+
BLECharacteristic::PROPERTY_WRITE |
60+
BLECharacteristic::PROPERTY_WRITE_NR
61+
);
62+
pCharacteristic->setCallbacks(new MyCallbacks());
63+
64+
// Start the service
65+
pService->start();
66+
67+
// Start advertising
68+
pServer->getAdvertising()->start();
69+
Serial.println("Waiting for a client to connect...");
70+
}
71+
72+
void loop() {
73+
// No need to implement anything here for this demo
74+
}

websocket/debug_sd.h

Lines changed: 218 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,29 @@
11
#include <Arduino.h>
2-
#include "pins_config.h" // Include your pin configuration file
3-
#include "FS.h"
4-
#include "SD_MMC.h"
2+
#include "pins_config.h" // Include your pin configuration file
3+
#include <WiFi.h> // Include the Wi-Fi library for ESP32
4+
#include <ESPping.h> // Include the ESPping library
5+
#include <FS.h>
6+
#include <SD_MMC.h> // Include SD_MMC library for SD card access
7+
#include <ArduinoJson.h> // Include ArduinoJson library
8+
#include <YAMLDuino.h> // Include YAMLDuino library for YAML parsing
9+
#include <time.h> // Include time library for timestamp
510

611
// Define SD card pins
712
#define PIN_SD_CMD 13 // CMD
813
#define PIN_SD_CLK 11 // CLK
914
#define PIN_SD_D0 12 // Data0
1015

16+
// Wi-Fi credentials and config parameters (to be read from SD card)
17+
String ssid = "";
18+
String password = "";
19+
String version = "";
20+
String last_read = "";
21+
22+
// Ping settings
23+
IPAddress pingAddress(8, 8, 8, 8); // IP address to ping
24+
int pingCount = 4; // Number of ping attempts
25+
int pingInterval = 1000; // Interval between pings in milliseconds
26+
1127
void listDir(fs::FS &fs, const char * dirname, uint8_t levels) {
1228
Serial.printf("Listing directory: %s\n", dirname);
1329

@@ -39,6 +55,94 @@ void listDir(fs::FS &fs, const char * dirname, uint8_t levels) {
3955
}
4056
}
4157

58+
bool readWiFiConfig(fs::FS &fs, const char * path) {
59+
Serial.printf("Reading Wi-Fi config from: %s\n", path);
60+
61+
File file = fs.open(path);
62+
if (!file) {
63+
Serial.println("Failed to open Wi-Fi config file");
64+
return false;
65+
}
66+
67+
// Read the entire file into a String
68+
String yamlContent = file.readString();
69+
file.close();
70+
71+
// Parse YAML content into ArduinoJson document
72+
StaticJsonDocument<1024> doc;
73+
DeserializationError error = deserializeYml(doc, yamlContent.c_str());
74+
75+
if (error) {
76+
Serial.print("Failed to parse YAML file: ");
77+
Serial.println(error.c_str());
78+
return false;
79+
}
80+
81+
// Extract values
82+
version = doc["version"] | "";
83+
last_read = doc["last_read"] | "";
84+
ssid = doc["settings"]["wifi"]["ssid"] | "";
85+
password = doc["settings"]["wifi"]["pass"] | "";
86+
87+
// Print the configuration values
88+
Serial.print("Version: ");
89+
Serial.println(version);
90+
Serial.print("Last Read: ");
91+
Serial.println(last_read);
92+
Serial.print("SSID: ");
93+
Serial.println(ssid);
94+
Serial.print("Password: ");
95+
Serial.println(password);
96+
97+
if (ssid.length() == 0 || password.length() == 0) {
98+
Serial.println("SSID or password not found in config file");
99+
return false;
100+
}
101+
102+
// Update last_read with current timestamp
103+
time_t now;
104+
time(&now);
105+
last_read = String((unsigned long)now);
106+
doc["last_read"] = last_read;
107+
108+
// Serialize the updated document back to YAML
109+
String updatedYamlContent;
110+
size_t bytesWritten = serializeYml(doc.as<JsonVariant>(), updatedYamlContent);
111+
112+
if (bytesWritten == 0) {
113+
Serial.println("Failed to serialize updated YAML content");
114+
return false;
115+
}
116+
117+
// Write the updated YAML content back to the file
118+
file = fs.open(path, FILE_WRITE);
119+
if (!file) {
120+
Serial.println("Failed to open config file for writing");
121+
return false;
122+
}
123+
124+
if (file.print(updatedYamlContent)) {
125+
Serial.println("Config file updated");
126+
} else {
127+
Serial.println("Failed to write to config file");
128+
file.close();
129+
return false;
130+
}
131+
file.close();
132+
133+
return true;
134+
}
135+
136+
void initTime() {
137+
configTime(0, 0, "pool.ntp.org", "time.nist.gov");
138+
Serial.print("Waiting for time synchronization");
139+
while (time(nullptr) < 100000) {
140+
Serial.print(".");
141+
delay(1000);
142+
}
143+
Serial.println(" done!");
144+
}
145+
42146
void setup() {
43147
Serial.begin(115200);
44148
delay(1000); // Wait for Serial Monitor to initialize
@@ -74,8 +178,118 @@ void setup() {
74178

75179
// List files in the root directory
76180
listDir(SD_MMC, "/", 0);
181+
182+
// Read Wi-Fi credentials from SD card
183+
if (!readWiFiConfig(SD_MMC, "/webscreen.yml")) {
184+
Serial.println("Failed to read Wi-Fi configuration");
185+
return;
186+
}
187+
188+
// Initialize LED pin
189+
pinMode(PIN_LED, OUTPUT);
190+
digitalWrite(PIN_LED, HIGH); // Turn off LED (assuming HIGH is off)
191+
192+
// Initialize Wi-Fi connection
193+
Serial.println("Connecting to Wi-Fi...");
194+
WiFi.mode(WIFI_STA); // Set Wi-Fi to station mode
195+
WiFi.begin(ssid.c_str(), password.c_str());
196+
197+
// Blink LED while connecting
198+
while (WiFi.status() != WL_CONNECTED) {
199+
digitalWrite(PIN_LED, LOW); // Turn LED on
200+
delay(250);
201+
digitalWrite(PIN_LED, HIGH); // Turn LED off
202+
delay(250);
203+
Serial.print(".");
204+
}
205+
206+
// Wi-Fi connected
207+
Serial.println("\nWi-Fi connected!");
208+
Serial.print("IP Address: ");
209+
Serial.println(WiFi.localIP());
210+
211+
// Display Wi-Fi signal strength
212+
Serial.print("Signal Strength (RSSI): ");
213+
Serial.print(WiFi.RSSI());
214+
Serial.println(" dBm");
215+
216+
// Turn LED on solid to indicate successful connection
217+
digitalWrite(PIN_LED, LOW); // Turn LED on
218+
219+
// Initialize Ping
220+
Serial.println("Initializing ping test...");
77221
}
78222

79223
void loop() {
80-
// Empty loop
224+
// Check Wi-Fi connection status
225+
if (WiFi.status() != WL_CONNECTED) {
226+
Serial.println("Wi-Fi disconnected!");
227+
digitalWrite(PIN_LED, HIGH); // Turn LED off
228+
229+
// Attempt to reconnect
230+
WiFi.disconnect();
231+
WiFi.begin(ssid.c_str(), password.c_str());
232+
233+
// Blink LED while reconnecting
234+
while (WiFi.status() != WL_CONNECTED) {
235+
digitalWrite(PIN_LED, LOW); // Turn LED on
236+
delay(250);
237+
digitalWrite(PIN_LED, HIGH); // Turn LED off
238+
delay(250);
239+
Serial.print(".");
240+
}
241+
242+
Serial.println("\nReconnected to Wi-Fi!");
243+
Serial.print("IP Address: ");
244+
Serial.println(WiFi.localIP());
245+
246+
// Display Wi-Fi signal strength
247+
Serial.print("Signal Strength (RSSI): ");
248+
Serial.print(WiFi.RSSI());
249+
Serial.println(" dBm");
250+
251+
// Turn LED on solid
252+
digitalWrite(PIN_LED, LOW); // Turn LED on
253+
}
254+
255+
// Perform ping test
256+
Serial.println("Pinging 8.8.8.8...");
257+
258+
int successfulPings = 0;
259+
int minTime = INT_MAX;
260+
int maxTime = 0;
261+
float totalTime = 0;
262+
263+
for (int i = 0; i < pingCount; i++) {
264+
// Send one ping
265+
int result = Ping.ping(pingAddress, 1);
266+
if (result > 0) {
267+
float time = Ping.averageTime();
268+
successfulPings++;
269+
totalTime += time;
270+
if (time < minTime) minTime = time;
271+
if (time > maxTime) maxTime = time;
272+
Serial.printf("Reply from %s: time=%.2f ms\n", pingAddress.toString().c_str(), time);
273+
} else {
274+
Serial.println("Request timed out.");
275+
}
276+
delay(pingInterval);
277+
}
278+
279+
// Display statistics
280+
Serial.println("Ping statistics for 8.8.8.8:");
281+
Serial.printf(" Packets: Sent = %d, Received = %d, Lost = %d (%d%% loss)\n",
282+
pingCount, successfulPings, pingCount - successfulPings,
283+
(100 * (pingCount - successfulPings) / pingCount));
284+
285+
if (successfulPings > 0) {
286+
Serial.println("Approximate round trip times in milli-seconds:");
287+
Serial.printf(" Minimum = %d ms, Maximum = %d ms, Average = %.2f ms\n",
288+
minTime, maxTime, totalTime / successfulPings);
289+
} else {
290+
Serial.println("No responses received.");
291+
}
292+
293+
// Wait before next ping test
294+
delay(10000); // Wait for 10 seconds before next test
81295
}

0 commit comments

Comments
 (0)