ESP32 Serial Monitor Status:
ets Jul 29 2019 12:21:46
rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0030,len:1448
load:0x40078000,len:14844
ho 0 tail 12 room 4
load:0x40080400,len:4
load:0x40080404,len:3356
entry 0x4008059c
Connecting to Wi-Fi...
.Connected to Wi-Fi
IP Address: 192.168.1.10
Received JSON data: Found ID #3 with confidence of 92Received JSON data: Found ID #6 with confidence of 131
Received JSON data: Election Results
Received JSON data: PTI:
Received JSON data: 1
Received JSON data: PPP:
Received JSON data: 0
Received JSON data: ANP:
Received JSON data: 0
Received JSON data: TotalVotes:
Received JSON data: 1
Received JSON data: Winner: PTI
Received JSON data: (100.00% of total votes)
Received JSON data: Sending JSON data: {"totalVotes":1,"PTI":1,"PPP":0,"ANP":0,"winner":"PTI"}
Received JSON data:
Failed to parse JSON: EmptyInput
Received JSON data: {"totalVotes":1,"PTI":1,"PPP":0,"ANP":0,"winner":"PTI"}
Parsed data:
Total Votes: 1
PTI Votes: 1
PPP Votes: 0
ANP Votes: 0
Winner: PTI
Sending data to server: totalVotes=1&PTI=1&PPP=0&ANP=0&winner=PTI
Error code: -1
Error message: connection refused
**ESP32 Code:**
```
`#include <WiFi.h>`
#include <HTTPClient.h>
#include <ArduinoJson.h>
// Wi-Fi credentials
const char* ssid = "^__Encrypted Air__^";
const char* password = "S3curP@ssW1f1";
// Server URL for sending data
const String serverUrl = "http://192.168.1.10/results.json";
// Buffer size for incoming serial data
const int bufferSize = 256;
// Global variables for storing results
int totalVotes = 0;
int PTI = 0;
int PPP = 0;
int ANP = 0;
String winner_name = "";
// Initialize Serial communication
void setup() {
Serial.begin(115200); // Initialize serial communication with Arduino
WiFi.begin(ssid, password);
Serial.println("Connecting to Wi-Fi...");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("Connected to Wi-Fi");
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());
}
void loop() {
// Check if there is incoming data from Arduino
if (Serial.available()) {
char jsonBuffer[bufferSize];
int bytesRead = Serial.readBytesUntil('\n', jsonBuffer, bufferSize - 1);
jsonBuffer[bytesRead] = '\0'; // Null-terminate the string
// Print the received data for debugging
Serial.print("Received JSON data: ");
Serial.println(jsonBuffer);
// Parse the JSON data
StaticJsonDocument<bufferSize> doc;
DeserializationError error = deserializeJson(doc, jsonBuffer);
if (error) {
Serial.print("Failed to parse JSON: ");
Serial.println(error.c_str());
return;
}
// Extract data from JSON
if (doc.containsKey("totalVotes") &&
doc.containsKey("PTI") &&
doc.containsKey("PPP") &&
doc.containsKey("ANP") &&
doc.containsKey("winner")) {
totalVotes = doc["totalVotes"];
PTI = doc["PTI"];
PPP = doc["PPP"];
ANP = doc["ANP"];
winner_name = doc["winner"].as<String>();
// Print the parsed values for debugging
Serial.println("Parsed data:");
Serial.print("Total Votes: ");
Serial.println(totalVotes);
Serial.print("PTI Votes: ");
Serial.println(PTI);
Serial.print("PPP Votes: ");
Serial.println(PPP);
Serial.print("ANP Votes: ");
Serial.println(ANP);
Serial.print("Winner: ");
Serial.println(winner_name);
// Send data to the Android application
sendToAndroidApp(totalVotes, PTI, PPP, ANP, winner_name);
} else {
Serial.println("JSON is missing some expected fields.");
}
}
delay(10000); // Wait for 10 seconds before checking again
}
void sendToAndroidApp(int totalVotes, int PTI, int PPP, int ANP, String winner_name) {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
http.begin(serverUrl);
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
String httpRequestData = "totalVotes=" + String(totalVotes) +
"&PTI=" + String(PTI) +
"&PPP=" + String(PPP) +
"&ANP=" + String(ANP) +
"&winner=" + winner_name;
Serial.print("Sending data to server: ");
Serial.println(httpRequestData);
int httpResponseCode = http.POST(httpRequestData);
if (httpResponseCode > 0) {
String response = http.getString();
Serial.print("Server response: ");
Serial.println(response);
} else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
Serial.print("Error message: ");
Serial.println(http.errorToString(httpResponseCode));
}
http.end();
} else {
Serial.println("Error: Not connected to Wi-Fi");
}
}
```
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
**Android Activity Code**
```
public class UserActivity extends AppCompatActivity {
private WebView webView;
private Button logoutButton;
private RequestQueue requestQueue;
private static final String RESULTS_URL = "http://192.168.1.10/results.json"; // Replace with your actual URL
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user);
// Initialize components
webView = findViewById(R.id.results_webview);
logoutButton = findViewById(R.id.user_logout_button);
requestQueue = Volley.newRequestQueue(this);
// Setup WebView
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
// Load Election Results from the server
fetchElectionResults();
// Logout button functionality
logoutButton.setOnClickListener(v -> {
Intent intent = new Intent(UserActivity.this, Login.class);
startActivity(intent);
finish();
});
}
private void fetchElectionResults() {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.GET,
RESULTS_URL,
null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
String htmlData = formatElectionResult(response);
webView.loadDataWithBaseURL(null, htmlData, "text/html", "UTF-8", null);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(UserActivity.this, "Failed to load results", Toast.LENGTH_SHORT).show();
}
}
);
requestQueue.add(jsonObjectRequest);
}
private String formatElectionResult(JSONObject json) {
try {
StringBuilder html = new StringBuilder();
html.append("<html><body>")
.append("<h2>Election Results</h2>")
.append("<table border='1' style='width:100%; border-collapse: collapse;'>")
.append("<tr><th>Party</th><th>Votes</th><th>Percentage</th></tr>");
html.append("<tr><td>PTI</td><td>").append(json.getInt("PTI")).append("</td><td>").append(json.getJSONObject("Percentages").getString("PTI")).append("</td></tr>")
.append("<tr><td>PPP</td><td>").append(json.getInt("PPP")).append("</td><td>").append(json.getJSONObject("Percentages").getString("PPP")).append("</td></tr>")
.append("<tr><td>ANP</td><td>").append(json.getInt("ANP")).append("</td><td>").append(json.getJSONObject("Percentages").getString("ANP")).append("</td></tr>")
.append("</table>")
.append("<p>Total Votes: ").append(json.getInt("TotalVotes")).append("</p>")
.append("<h3>Winner: ").append(json.getString("Winner")).append("</h3>")
.append("</body></html>");
return html.toString();
} catch (Exception e) {
e.printStackTrace();
return "<html><body><p>Error loading results</p></body></html>";
}
}
}
```