Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Reconnection Attempts and Logging for Wi-Fi Checker (Issue #347) #376

Merged
merged 7 commits into from
Nov 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 72 additions & 17 deletions Auto WiFi Check/wifi_checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,44 +2,99 @@
import subprocess
import sys
import time
from datetime import datetime
import logging
import schedule as sc

# Create the log file if it doesn't already exist
LOG_FILE = "wifi_status_log.txt"
PING_HOST = "www.google.com"

try:
with open(LOG_FILE, 'x') as file:
file.write("Logs:\n")
print(f"File '{LOG_FILE}' created successfully.")
except FileExistsError:
print(f"File '{LOG_FILE}' already exists.")

# Set up logging to log to a file with timestamps
logging.basicConfig(filename=LOG_FILE,
level=logging.INFO,
format='%(asctime)s - %(message)s',
filemode='a') # Append mode

def enable():
subprocess.call("netsh interface set interface Wi-Fi enabled")
print("Turning On the laptop WiFi")
try:
subprocess.call("netsh interface set interface Wi-Fi enabled", shell=True)
print("Turning On the laptop WiFi")
logging.info("WiFi enabled")
except Exception as e:
print(f"Failed to enable WiFi: {e}")
logging.error(f"Failed to enable WiFi: {e}")

def disable():
subprocess.call("netsh interface set interface Wi-Fi disabled")
print("Turning Off the laptop WiFi")

try:
subprocess.call("netsh interface set interface Wi-Fi disabled", shell=True)
print("Turning Off the laptop WiFi")
logging.info("WiFi disabled")
except Exception as e:
print(f"Failed to disable WiFi: {e}")
logging.error(f"Failed to disable WiFi: {e}")


def job():
if subprocess.call("netsh interface set interface Wi-Fi enabled") == 0:
try:
subprocess.call("netsh interface set interface Wi-Fi enabled", shell=True)
print("WiFi is enabled and connected to internet")
hostname = "www.google.com"
response = subprocess.call("ping -n 1 " + hostname)
logging.info("WiFi is enabled and connected to the internet.")

response = subprocess.call(f"ping -n 1 {PING_HOST}", shell=True)

if response == 1:
print("Your Connection is not working")
disable()
time.sleep(1)
enable()
logging.warning("WiFi connection not working, ping failed.")

attempt_counter = 0
max_attempts = 3

while attempt_counter < max_attempts:
print(f"Attempt {attempt_counter + 1} to reconnect...")
logging.info(f"Attempt {attempt_counter + 1} to reconnect...")

disable()
time.sleep(1)
enable()

time.sleep(5)

response = subprocess.call(f"ping -n 1 {PING_HOST}", shell=True)
if response == 0:
print("Reconnection successful!")
logging.info("Reconnection successful!")
break
else:
print(f"Reconnection attempt {attempt_counter + 1} failed.")
logging.warning(f"Reconnection attempt {attempt_counter + 1} failed.")

attempt_counter += 1

if attempt_counter == max_attempts and response != 0:
print(f"Failed to reconnect after {max_attempts} attempts.")
logging.error(f"Failed to reconnect after {max_attempts} attempts.")
except Exception as e:
print(f"Error during WiFi check: {e}")
logging.error(f"Error during WiFi check: {e}")

def is_admin():
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
except Exception as e:
logging.error(f"Admin check failed: {e}")
return False

if is_admin():
# job()
sc.every(50).seconds.do(job)
else:
ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)


while True:
sc.run_pending()
time.sleep(1)
time.sleep(1)
hasan-py marked this conversation as resolved.
Show resolved Hide resolved
1 change: 1 addition & 0 deletions Auto WiFi Check/wifi_status_log.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what is the need for this file? and this line specifically? 

Copy link
Contributor Author

@Badis213 Badis213 Nov 12, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The wifi_status_log.txt file is set up to capture logs from Wi-Fi connection events. Since it only starts filling when the code runs, it’s currently empty. Let me know if you’d prefer I remove it from the repository.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you try to add the logic inside the script? This means that when the logging starts to capture, it should create the file automatically. That means there shouldn't be any file initially, but when the script runs and captures the log, it should create the file and then insert the data.

you can follow this code as reference:

file_name = "example.txt"

try:
    with open(file_name, 'x') as file:
        file.write("This is a new file created only if it didn't exist.")
    print(f"File '{file_name}' created successfully.")
except FileExistsError:
    print(f"File '{file_name}' already exists.")

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I absolutely can, I'll do that today.

Copy link
Contributor Author

@Badis213 Badis213 Nov 18, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Everything is done.
Here are the updates I made to the script:

Automatic log file creation:
The script now checks if the log file exists. If not, it automatically creates the file before writing any logs.

Improved error handling:
Added better error handling for netsh and ping commands to ensure the script behaves more reliably in different scenarios.

Constants for better configuration:
Extracted key values like the log file name and ping target into constants for easier customization.

I tested everything, and it works as expected. Below is the log file when the WiFi is manually disabled:

2024-11-18 19:15:02,500 - WiFi is enabled and connected to the internet.
2024-11-18 19:15:02,527 - WiFi connection not working, ping failed.
2024-11-18 19:15:02,527 - Attempt 1 to reconnect...
2024-11-18 19:15:07,146 - WiFi disabled
2024-11-18 19:15:11,814 - WiFi enabled
2024-11-18 19:15:16,864 - Reconnection attempt 1 failed.
2024-11-18 19:15:16,864 - Attempt 2 to reconnect...
2024-11-18 19:15:21,157 - WiFi disabled
2024-11-18 19:15:23,870 - WiFi enabled
2024-11-18 19:15:28,926 - Reconnection attempt 2 failed.
2024-11-18 19:15:28,936 - Attempt 3 to reconnect...
2024-11-18 19:15:33,427 - WiFi disabled
2024-11-18 19:15:35,974 - WiFi enabled
2024-11-18 19:15:41,098 - Reconnection successful!

This comment was marked as resolved.