#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <WebServer.h>
#include <WebSocketsServer.h>
#include <Ticker.h>
const char* ssid = "Wokwi-GUEST";
const char* password = "";
WebServer server;
WebSocketsServer webSocket = WebSocketsServer(81);
Ticker timer;
bool read_data = false;
String road = "";
String city = "";
String state = "";
String postcode = "";
String country = "";
// Predefined list of coordinates
const float predefinedCoordinates[][2] = {
{12.9716, 77.5946}, // Bangalore, India
{16.793528, 80.823083}, // Junction of I3
{16.793861, 80.822083},
{16.794472, 80.823472},
{16.794139, 80.824500}
// Add more coordinates as needed
};
const char webpage[] PROGMEM = R"=====(
<!DOCTYPE html>
<html>
<head>
<style>
/* Define your CSS rules here */
.container {
font-family: sans-serif;
max-width: 60%;
margin: auto;
padding: 20px;
}
h1 {
text-align: center;
margin-bottom: 30px;
}
.divider {
height: 1px;
background-color: #ccc;
margin: 20px 0;
}
.Details,
.Location {
color: #555;
display: grid;
grid-template-columns: auto auto;
}
.section li {
color: #555;
line-height: 300%;
}
</style>
</head>
<body>
<div class="container">
<h1>Patient Details</h1>
<div class="Details" style="padding-left: 40px" id="patientDetails">
<p>Name: Loading...</p>
<p>Age: Loading...</p>
<p>Gender: Loading...</p>
<p>Condition: Loading...</p>
<p>Medications: Loading...</p>
</div>
<div class="divider"></div>
<div class="section">
<h3>Patient Vital Signs:</h3>
<ul class="Details" style="list-style: none">
<li id="heartRate">Heart Rate: Loading...</li>
<li id="bloodPressure">Blood Pressure: Loading...</li>
<li id="oxygenSaturation">Oxygen Saturation: Loading...</li>
<li id="bodyTemperature">Body Temperature: Loading...</li>
</ul>
</div>
<div class="divider"></div>
<div class="section">
<h3>Location:</h3>
<div class="Location" style="padding-left: 40px">
<p id="location">Location: Loading...</p>
<p id="eta">ETA: Loading...</p>
</div>
</div>
</div>
<script>
var Socket;
// Function to initialize WebSocket connection
function init() {
Socket = new WebSocket('ws://' + window.location.hostname + ':81/');
Socket.onopen = function() {
console.log("WebSocket connection opened");
};
Socket.onmessage = function (event) {
processCommand(event);
};
Socket.onclose = function(event) {
console.log("WebSocket connection closed. Reconnecting...");
setTimeout(init, 2000); // Attempt to reconnect after 2 seconds
};
}
// Function to process incoming data from the server
function processCommand(event) {
var data = JSON.parse(event.data);
// Update patient details
document.getElementById('patientDetails').innerHTML = `
<p>Name: ${data.name}</p>
<p>Age: ${data.age}</p>
<p>Gender: ${data.gender}</p>
<p>Condition: ${data.condition}</p>
<p>Medications: ${data.medications}</p>
`;
// Update vital signs
document.getElementById('heartRate').innerText = 'Heart Rate: ' + data.heartRate + ' bpm';
document.getElementById('bloodPressure').innerText = 'Blood Pressure: ' + data.bloodPressure;
document.getElementById('oxygenSaturation').innerText = 'Oxygen Saturation: ' + data.oxygenSaturation + '%';
document.getElementById('bodyTemperature').innerText = 'Body Temperature: ' + data.bodyTemperature + '°C';
// Update location
document.getElementById('location').innerText = 'Location: ' + data.location;
document.getElementById('eta').innerText = 'ETA: ' + data.eta;
}
// Event listener to initialize WebSocket connection when the window loads
window.onload = function (event) {
init();
}
</script>
</body>
</html>
)=====";
unsigned long lastDataSentTime = 0;
const unsigned long dataInterval = 2000; // Delay between data packets in milliseconds
void setup() {
WiFi.begin(ssid,password);
Serial.begin(115200);
Serial.print("Connecting to WiFi :");
while(WiFi.status() != WL_CONNECTED) {
Serial.print("-");
delay(500);
}
Serial.print("Connected to WiFi :-");
Serial.print(ssid);
Serial.println();
Serial.print("IP Address (AP): "); Serial.println(WiFi.localIP());
server.on("/",[](){
server.send_P(200, "text/html", webpage);
});
server.begin();
webSocket.begin();
timer.attach(0.1, readData);
}
void readData() {
read_data = true;
}
void processGPSLocation(float latitude, float longitude) {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
// Craft the request URL for OpenStreetMap Nominatim API
String url = "https://nominatim.openstreetmap.org/reverse?format=json&lat=";
url += String(latitude, 6);
url += "&lon=";
url += String(longitude, 6);
Serial.print("Requesting URL: ");
Serial.println(url);
http.begin(url);
int httpCode = http.GET();
if (httpCode > 0) {
if (httpCode == HTTP_CODE_OK) {
String payload = http.getString();
Serial.println("Response:");
// Reduce the capacity of the JSON document to minimize memory usage
DynamicJsonDocument doc(512);
deserializeJson(doc, payload);
JsonObject address = doc.as<JsonObject>();
road = String(static_cast<const char*>(address["address"]["road"]));
city = String(static_cast<const char*>(address["address"]["city"]));
state = String(static_cast<const char*>(address["address"]["state"]));
postcode = String(static_cast<const char*>(address["address"]["postcode"]));
country = String(static_cast<const char*>(address["address"]["country"]));
Serial.print("Road: ");
Serial.println(road);
Serial.print("City: ");
Serial.println(city);
Serial.print("State: ");
Serial.println(state);
Serial.print("Postcode: ");
Serial.println(postcode);
Serial.print("Country: ");
Serial.println(country);
} else {
Serial.print("HTTP request failed with error code: ");
Serial.println(httpCode);
}
} else {
Serial.println("Error in HTTP request. Check your network connection.");
}
http.end();
}
}
void GPS(){
smartdelay_gps(1000);
// If GPS is not valid, pick coordinates randomly from the predefined list
int numCoordinates = sizeof(predefinedCoordinates) / sizeof(predefinedCoordinates[0]);
int randomIndex = random(0, numCoordinates);
float lat = predefinedCoordinates[randomIndex][0];
float lng = predefinedCoordinates[randomIndex][1];
processGPSLocation(lat, lng);
}
static void smartdelay_gps(unsigned long ms) {
unsigned long start = millis();
do {
} while (millis() - start < ms);
}
void sendData() {
unsigned long currentTime = millis();
if (read_data && (currentTime - lastDataSentTime >= dataInterval)) {
// Generate random values for patient details
String name = "John Doe";
int age = random(20, 80);
String gender = "Male";
String condition = "Stable";
String medications = "Aspirin";
// Generate random values for vital signs
int heartRate = random(60, 100);
String bloodPressure = String(random(100, 160)) + "/" + String(random(60, 100));
int oxygenSaturation = random(95, 100);
float bodyTemperature = random(360, 380) / 10.0; // Random temperature between 36.0°C and 38.0°C
// Create JSON string with acquired address and random values
String json = "{\"name\":\"" + name + "\",\"age\":" + age + ",\"gender\":\"" + gender + "\",\"condition\":\"" + condition + "\",\"medications\":\"" + medications + "\",\"heartRate\":" + heartRate + ",\"bloodPressure\":\"" + bloodPressure + "\",\"oxygenSaturation\":" + oxygenSaturation + ",\"bodyTemperature\":" + bodyTemperature + ",\"location\":\"" + city + ", " + country + "\",\"eta\":\"10 minutes\"}";
// Send JSON string over WebSocket to all connected clients
Serial.print("Sending data: ");
Serial.println(json);
webSocket.broadcastTXT(json.c_str(), json.length());
// Reset read_data flag and update lastDataSentTime
read_data = false;
lastDataSentTime = currentTime;
}
}
void loop() {
webSocket.loop();
server.handleClient();
GPS(); // Call the GPS function to update address variables
sendData(); // Send data to WebSocket clients
}