#include <SPI.h>
#include <SD.h>
#include <WiFiClient.h>
#include <WiFiClientSecure.h>
#include <HTTPClient.h>
#include <WiFi.h>
#define SD_CS 5
const char* path="/sourceF.txt";//path for sd card
//url for http
const char* url="https://raw.githubusercontent.com/dee362-lab/smart-parking-system/main/highfile";
//wifi credential
const char* username="Wokwi-GUEST";
const char* password="";
//creat the object
HTTPClient http;
WiFiClientSecure client;
//cheking wifi connectivity
void wificheking(){
int wifitry=0;
while((WiFi.status()!=WL_CONNECTED)){
Serial.println("conecting wifi..");
wifitry+=1;
delay(500);
if(wifitry>500){
Serial.println("fail to connect wifi");
return;
}
}
Serial.println("Wifi is connected");
}
//for downloading the file
void downloadfile(const char* path,const char* url){
client.setInsecure();
http.setTimeout(10000); // Set timeout to 10 seconds
if (!http.begin(client, url)) { // Use WiFiClientSecure for HTTPS
Serial.println("Failed to connect to server");
return;
}
SD.begin();
if (!SD.begin(SD_CS)) {
Serial.println("Card Mount Failed");
return;
}
int httpres=http.GET();
if(httpres==200){
File file=SD.open(path,"w");
if(!file){
Serial.println("cannot open the file ");
return;
}
WiFiClient* stream = http.getStreamPtr();
uint8_t buffer[1024];
size_t size;
unsigned long start = millis();
int totalbyte=0;
while (http.connected()) {
if (stream->available()) {
size = stream->read(buffer, sizeof(buffer));
if (size > 0) {
file.write(buffer, size);
totalbyte += size;
}
}
}
file.close();
unsigned long duration = millis() - start;
float speed = (totalbyte / 1024.0) / (duration / 1000.0);
Serial.printf("File downloaded and saved to SD card in %lu ms\n", duration);
Serial.printf("total bytes %d \n",totalbyte);
Serial.printf("total download spedd is %d kBps\n",speed);
}
else {
Serial.printf("http error %d",httpres);
}
http.end();
}
void readfile(const char* path){
File file=SD.open(path,"r");
if(!file){
Serial.print("cannnot oen the file for reading");
}
while(file.available()){
Serial.write(file.read());
}
file.close();
}
void setup() {
Serial.begin(115200);
WiFi.begin(username,password);
wificheking();
downloadfile(path,url);
}
void loop() {
// Nothing here
}