11# SPDX-FileCopyrightText: 2018 Mikey Sklar for Adafruit Industries
22#
33# SPDX-License-Identifier: MIT
4-
4+ # Modified by Jonathan Seyfert, 2022-01-22
5+ # to keep code from crashing when WiFi or IP is unavailable
56from subprocess import Popen , PIPE
6- from time import sleep
7+ from time import sleep , perf_counter
78from datetime import datetime
89import board
910import digitalio
2930
3031# looking for an active Ethernet or WiFi device
3132def find_interface ():
33+ # dev_name = 0 # sets dev_name so that function does not return Null and crash code
3234 find_device = "ip addr show"
3335 interface_parse = run_cmd (find_device )
3436 for line in interface_parse .splitlines ():
3537 if "state UP" in line :
3638 dev_name = line .split (':' )[1 ]
37- return dev_name
39+ return dev_name
40+ return 1 # avoids returning Null if "state UP" doesn't exist
3841
3942# find an active IP on the first LIVE network device
4043def parse_ip ():
41- find_ip = "ip addr show %s" % interface
44+ if interface == 1 : # if true, no device is in "state UP", skip IP check
45+ return "not assigned " # display "IP not assigned"
46+ ip = "0"
4247 find_ip = "ip addr show %s" % interface
4348 ip_parse = run_cmd (find_ip )
4449 for line in ip_parse .splitlines ():
4550 if "inet " in line :
4651 ip = line .split (' ' )[5 ]
4752 ip = ip .split ('/' )[0 ]
48- return ip
53+ return ip # returns IP address, if found
54+ return "pending " # display "IP pending" when "state UP", but no IPv4 address yet
4955
5056# run unix shell command, return as ASCII
5157def run_cmd (cmd ):
@@ -56,12 +62,19 @@ def run_cmd(cmd):
5662# wipe LCD screen before we start
5763lcd .clear ()
5864
65+
5966# before we start the main loop - detect active network device and ip address
60- sleep ( 2 )
67+ # set timer to = perf_counter(), for later use in IP update check
6168interface = find_interface ()
6269ip_address = parse_ip ()
70+ timer = perf_counter ()
6371
6472while True :
73+ # check for new IP addresses, at a slower rate than updating the clock
74+ if perf_counter () - timer >= 15 :
75+ interface = find_interface ()
76+ ip_address = parse_ip ()
77+ timer = perf_counter ()
6578
6679 # date and time
6780 lcd_line_1 = datetime .now ().strftime ('%b %d %H:%M:%S\n ' )
@@ -72,4 +85,4 @@ def run_cmd(cmd):
7285 # combine both lines into one update to the display
7386 lcd .message = lcd_line_1 + lcd_line_2
7487
75- sleep (2 )
88+ sleep (1 )
0 commit comments