Software source reference
"""
Contains a script, which is by default run every 15 minutes, to check the connection to the internet and solve
possible problems if no connection could be established.
Authors:
Min Tai Yap
"""
import subprocess
import time
import os
import sys
import datetime
[docs]
def run_command(command):
"""
Runs a shell command.
:param command: Command as string
:returns: A tuple containing responses in stdout and stderr, as well as the resulting CompletedProcess object as a whole
"""
result = subprocess.run(command, shell=True, text=True, capture_output=True)
return result.stdout.strip(), result.stderr.strip(), result
[docs]
def check_ttyUSB():
"""
Checks if the Waveshare module is connected to the USB port corresponding to /dev/ttyUSB2 and that a connection through
the USB port can be established. Therefore, it is assumed that the Waveshare module is connected to the right USB port.
If the module is either not connected or a connection cannot be established with the module, the Raspi is rebooted.
"""
stdout, _, result = run_command("ls /dev/ttyUSB*")
print(result)
print("")
if "/dev/ttyUSB2" in stdout:
print(f"'/dev/ttyUSB2' found in the list: {stdout}")
print("")
else:
subprocess.Popen(["sudo", "reboot"])
[docs]
def check_internet():
"""
Checks if the device has a connection to the internet by pinging 8.8.8.8.
:returns: True if the ping was successful, False otherwise
"""
stdout, stderr, result = run_command("ping -c 4 8.8.8.8")
print(result)
if stderr:
return False
if "0% packet loss" in stdout and "Destination Host Unreachable" not in stdout:
return True
return False
[docs]
def main():
"""
Checks connectivity to the internet. Our default configuration runs this script every 15 minutes.
If the raspi is not connected to the internet, this script first checks if the communication with
the Waveshare module is possible. If that is the case, the script tries to restart the connecting
to the internet. If this step also fails, the internet connection via the mobile network is turned
off until this script is run the next time.
"""
try:
# Print current detetime
print(datetime.datetime.now())
# ------------------------- Block 1 -----------------------------
# Initial internet check
print("Checking initial internet connectivity...")
if check_internet():
print("Internet connection is already up.")
return
# ------------------------- Block 2 -----------------------------
# No internet, proceed with running pon and other commands
print("No initial internet connection. Turn off provider. Running 'sudo poff provider'...")
# List out all the available ttyUSB channel
check_ttyUSB()
#_, _, result = run_command("ls /dev/ttyUSB*")
#print(result)
#print("")
subprocess.Popen(["sh", "-c", "sudo poff provider"])
time.sleep(3)
print("Running 'sudo pon provider'...")
subprocess.Popen(["sh", "-c", "sudo pon provider"])
# Wait a few seconds to ensure the command has time to execute
time.sleep(10)
# ------------------------- Block 3 -----------------------------
# Check for IFace with ppp0 using "route -n"
print("Checking for IFace with ppp0...")
stdout, stderr, _ = run_command("sudo route -n")
if stderr:
print(f"Error running 'route -n': {stderr}")
return
if "ppp0" in stdout:
print("IFace with ppp0 found.")
# Run "sudo route add default ppp0"
print("Adding default route to ppp0...")
stdout, stderr, _ = run_command("sudo route add default ppp0")
if stderr:
print(f"Error running 'sudo route add default ppp0': {stderr}")
return
time.sleep(10)
# Check internet connection with "ping 8.8.8.8"
print("Pinging 8.8.8.8 to check internet connection...")
if check_internet():
print("Internet connection is up.")
else:
print("No internet connection after pon. Running 'sudo poff provider' and wait for the next connection")
run_command("sudo poff provider")
else:
print("IFace with ppp0 not found.")
#subprocess.Popen(["sudo", "reboot"])
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
main()
