I've been tinkering around with making a fancy clock on a Raspberry Pi B. This little application will sync the Pi's time with an NTP server, then display it using toilet
so it's nice n' big & centered on a monitor. This was made for a GUI-less Pi, and I'm looking to hopefully make it more efficient. Right now the seconds aren't a uniform duration (the time.sleep(0.3)
is there to even it out), and I'm sure it's because the Pi is struggling to keep up with my newbie code.
#!/usr/bin/env python
import subprocess
import sys
import os
import time
from datetime import datetime
import ntplib
NTP_MISS = 0
def display_clock():
#Clock Positioning
rows, columns = os.popen('stty size', 'r').read().split()
h_pos = int(int(columns) / 6)
v_pos = "\033[" + str(int(int(rows) / 6)) + ";0H"
#Initialization
check_ntp_time = time.time()
os.system('setterm --cursor off -powersave off')
subprocess.call("clear")
#Meat & Potatoes
try:
while check_ntp_time + 86400 >= time.time():
current_date = subprocess.check_output(["date", "+%r"]).strip().decode("utf-8")
current_date = " " * h_pos + current_date
sys.stdout.write(v_pos + subprocess.check_output(["toilet", "-w 200", current_date]).decode("utf-8"))
sys.stdout.flush()
time.sleep(0.3)
except KeyboardInterrupt:
print("Closing NTP Clock")
os.system('setterm --cursor on -powersave on')
subprocess.call("clear")
print("Closed NTP Clock")
exit()
#Update time using NTP pool.
get_ntp_time()
def get_ntp_time():
call = ntplib.NTPClient()
while True:
try:
#Try to connect to the NTP pool...
response = call.request('pool.ntp.org')
print("Time updated!")
break
except:
NTP_MISS += 1
if NTP_MISS >= 5:
print("NTP server unavailable for too long! Terminating...")
os.system('setterm --cursor on -powersave on')
subprocess.call("clear")
print("NTP Clock failed. Server unresponsive for too long.")
exit()
#Not a huge deal if we miss it, just continue displaying the clock.
print("Could not connect to pool.")
display_clock()
#If we get a response, update the system time.
t = datetime.fromtimestamp(response.tx_time)
t = t.strftime('%Y-%m-%d %I:%M:%S %Z')
set_string = "--set=" + t
subprocess.call(["date", set_string])
display_clock()
if __name__ == "__main__":
display_clock()
I'd prefer to use the subprocess
instead of os.system
, but for some reason using subprocess
with setterm
returned a "command not found" error. So that's why I'm using os.system
instead.
What all can I do to optimize & clean up this code?