Skip to content

Commit db49396

Browse files
committed
Add logger to replace print()
1 parent c1fb95f commit db49396

9 files changed

+60
-49
lines changed

library/config.py

+5-13
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,16 @@
1-
import logging
21
import os
32
import queue
43
import sys
54
import threading
65

76
import yaml
87

8+
from library.log import logger
99

10-
def load_yaml(configfile):
11-
if not os.path.exists(configfile):
12-
logging.critical("No YAML file found")
13-
exit()
1410

11+
def load_yaml(configfile):
1512
with open(configfile, "r") as stream:
16-
try:
17-
yamlconfig = yaml.safe_load(stream)
18-
except yaml.YAMLError:
19-
logging.critical("Failed loading YAML configuration file")
20-
exit()
21-
13+
yamlconfig = yaml.safe_load(stream)
2214
return yamlconfig
2315

2416

@@ -27,11 +19,11 @@ def load_yaml(configfile):
2719

2820
try:
2921
theme_path = "res/themes/" + CONFIG_DATA['config']['THEME'] + "/"
30-
print("Loading theme", CONFIG_DATA['config']['THEME'], "from ", theme_path + "theme.yaml")
22+
logger.info("Loading theme %s from %s" % (CONFIG_DATA['config']['THEME'], theme_path + "theme.yaml"))
3123
THEME_DATA = load_yaml(theme_path + "theme.yaml")
3224
THEME_DATA['PATH'] = theme_path
3325
except:
34-
print("Theme not found or contains errors!")
26+
logger.error("Theme not found or contains errors!")
3527
try:
3628
sys.exit(0)
3729
except:

library/display.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from library import config
22
from library.lcd_comm_rev_a import LcdCommRevA
33
from library.lcd_comm_rev_b import LcdCommRevB
4+
from library.log import logger
45

56
THEME_DATA = config.THEME_DATA
67
CONFIG_DATA = config.CONFIG_DATA
@@ -21,7 +22,7 @@ def __init__(self):
2122
elif CONFIG_DATA["display"]["REVISION"] == "B":
2223
self.lcd = LcdCommRevB()
2324
else:
24-
print("Unknown display revision '", CONFIG_DATA["display"]["REVISION"], "'")
25+
logger.error("Unknown display revision '", CONFIG_DATA["display"]["REVISION"], "'")
2526

2627
def initialize_display(self):
2728
# Reset screen in case it was in an unstable state (screen is also cleared)
@@ -42,7 +43,7 @@ def initialize_display(self):
4243
def display_static_images(self):
4344
if THEME_DATA['static_images']:
4445
for image in THEME_DATA['static_images']:
45-
print(f"Drawing Image: {image}")
46+
logger.debug(f"Drawing Image: {image}")
4647
self.lcd.DisplayBitmap(
4748
bitmap_path=THEME_DATA['PATH'] + THEME_DATA['static_images'][image].get("PATH"),
4849
x=THEME_DATA['static_images'][image].get("X", 0),
@@ -54,7 +55,7 @@ def display_static_images(self):
5455
def display_static_text(self):
5556
if THEME_DATA['static_text']:
5657
for text in THEME_DATA['static_text']:
57-
print(f"Drawing Text: {text}")
58+
logger.debug(f"Drawing Text: {text}")
5859
self.lcd.DisplayText(
5960
text=THEME_DATA['static_text'][text].get("TEXT"),
6061
x=THEME_DATA['static_text'][text].get("X", 0),

library/lcd_comm.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
from PIL import Image, ImageDraw, ImageFont
66

77
from library import config
8+
from library.log import logger
89

910
CONFIG_DATA = config.CONFIG_DATA
1011
THEME_DATA = config.THEME_DATA
@@ -27,7 +28,7 @@ def get_theme_orientation() -> Orientation:
2728
elif THEME_DATA["display"]["DISPLAY_ORIENTATION"] == 'reverse_landscape':
2829
return Orientation.REVERSE_LANDSCAPE
2930
else:
30-
print("Orientation '", THEME_DATA["display"]["DISPLAY_ORIENTATION"], "' unknown, using portrait")
31+
logger.warning("Orientation '", THEME_DATA["display"]["DISPLAY_ORIENTATION"], "' unknown, using portrait")
3132
return Orientation.PORTRAIT
3233

3334

@@ -50,10 +51,10 @@ def openSerial(self):
5051
if CONFIG_DATA['config']['COM_PORT'] == 'AUTO':
5152
lcd_com_port = self.auto_detect_com_port()
5253
self.lcd_serial = serial.Serial(lcd_com_port, 115200, timeout=1, rtscts=1)
53-
print(f"Auto detected comm port: {lcd_com_port}")
54+
logger.debug(f"Auto detected comm port: {lcd_com_port}")
5455
else:
5556
lcd_com_port = CONFIG_DATA["config"]["COM_PORT"]
56-
print(f"Static comm port: {lcd_com_port}")
57+
logger.debug(f"Static comm port: {lcd_com_port}")
5758
self.lcd_serial = serial.Serial(lcd_com_port, 115200, timeout=1, rtscts=1)
5859

5960
@staticmethod

library/lcd_comm_rev_a.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
from serial.tools.list_ports import comports
55

66
from library.lcd_comm import *
7+
from library.log import logger
78

89

910
class Command(IntEnum):
@@ -23,7 +24,6 @@ def __init__(self):
2324

2425
def __del__(self):
2526
try:
26-
print("close serial")
2727
self.lcd_serial.close()
2828
except:
2929
pass
@@ -60,7 +60,7 @@ def WriteData(self, byteBuffer: bytearray):
6060
self.lcd_serial.write(bytes(byteBuffer))
6161
except serial.serialutil.SerialTimeoutException:
6262
# We timed-out trying to write to our device, slow things down.
63-
print("(Write data) Too fast! Slow down!")
63+
logger.warn("(Write data) Too fast! Slow down!")
6464

6565
def SendLine(self, line: bytes):
6666
config.update_queue.put((self.WriteLine, [line]))
@@ -70,14 +70,14 @@ def WriteLine(self, line: bytes):
7070
self.lcd_serial.write(line)
7171
except serial.serialutil.SerialTimeoutException:
7272
# We timed-out trying to write to our device, slow things down.
73-
print("(Write line) Too fast! Slow down!")
73+
logger.warn("(Write line) Too fast! Slow down!")
7474

7575
def InitializeComm(self):
7676
# HW revision A does not need init commands
7777
pass
7878

7979
def Reset(self):
80-
print("Display reset...")
80+
logger.info("Display reset...")
8181
# Reset command bypasses queue because it is run when queue threads are not yet started
8282
self.SendCommand(Command.RESET, 0, 0, 0, 0, bypass_queue=True)
8383
# Wait for display reset then reconnect
@@ -106,7 +106,7 @@ def SetBrightness(self, level: int = CONFIG_DATA["display"]["BRIGHTNESS"]):
106106
self.SendCommand(Command.SET_BRIGHTNESS, level_absolute, 0, 0, 0)
107107

108108
def SetBackplateLedColor(self, led_color: tuple[int, int, int] = THEME_DATA['display']["DISPLAY_RGB_LED"]):
109-
print("HW revision A does not support backplate LED color setting")
109+
logger.info("HW revision A does not support backplate LED color setting")
110110
pass
111111

112112
def SetOrientation(self, orientation: Orientation = get_theme_orientation()):

library/lcd_comm_rev_b.py

+6-5
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from serial.tools.list_ports import comports
44

55
from library.lcd_comm import *
6+
from library.log import logger
67

78

89
class Command(IntEnum):
@@ -77,7 +78,7 @@ def WriteData(self, byteBuffer: bytearray):
7778
self.lcd_serial.write(bytes(byteBuffer))
7879
except serial.serialutil.SerialTimeoutException:
7980
# We timed-out trying to write to our device, slow things down.
80-
print("(Write data) Too fast! Slow down!")
81+
logger.warn("(Write data) Too fast! Slow down!")
8182

8283
def SendLine(self, line: bytes):
8384
config.update_queue.put((self.WriteLine, [line]))
@@ -87,7 +88,7 @@ def WriteLine(self, line: bytes):
8788
self.lcd_serial.write(line)
8889
except serial.serialutil.SerialTimeoutException:
8990
# We timed-out trying to write to our device, slow things down.
90-
print("(Write line) Too fast! Slow down!")
91+
logger.warn("(Write line) Too fast! Slow down!")
9192

9293
def Hello(self):
9394
hello = [ord('H'), ord('E'), ord('L'), ord('L'), ord('O')]
@@ -97,11 +98,11 @@ def Hello(self):
9798
response = self.lcd_serial.read(10)
9899

99100
if len(response) != 10:
100-
print("Device not recognised (short response to HELLO)")
101+
logger.warn("Device not recognised (short response to HELLO)")
101102
if response[0] != Command.HELLO or response[-1] != Command.HELLO:
102-
print("Device not recognised (bad framing)")
103+
logger.warn("Device not recognised (bad framing)")
103104
if [x for x in response[1:6]] != hello:
104-
print("Device not recognised (No HELLO; got %r)" % (response[1:6],))
105+
logger.warn("Device not recognised (No HELLO; got %r)" % (response[1:6],))
105106
# The HELLO response here is followed by:
106107
# 0x0A, 0x12, 0x00
107108
# It is not clear what these might be.

library/log.py

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
# Configure logging format
2+
import logging
3+
4+
logging.basicConfig(# format='%(asctime)s [%(levelname)s] %(message)s in %(pathname)s:%(lineno)d',
5+
format="%(asctime)s [%(levelname)s] %(message)s",
6+
handlers=[
7+
# logging.FileHandler("log.log", mode='w'), # Log in textfile (erased at each start)
8+
logging.StreamHandler() # Log also in console
9+
],
10+
datefmt='%H:%M:%S')
11+
12+
logger = logging.getLogger('turing')
13+
logger.setLevel(logging.DEBUG) # Lowest log level : print all messages

library/scheduler.py

+9-8
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
import library.config as config
88
import library.stats as stats
9+
from library.log import logger
910

1011
THEME_DATA = config.THEME_DATA
1112

@@ -64,61 +65,61 @@ def wrap(
6465
@schedule(timedelta(seconds=THEME_DATA['STATS']['CPU']['PERCENTAGE'].get("INTERVAL", None)).total_seconds())
6566
def CPUPercentage():
6667
""" Refresh the CPU Percentage """
67-
# print("Refresh CPU Percentage")
68+
# logger.debug("Refresh CPU Percentage")
6869
stats.CPU.percentage()
6970

7071

7172
@async_job("CPU_Frequency")
7273
@schedule(timedelta(seconds=THEME_DATA['STATS']['CPU']['FREQUENCY'].get("INTERVAL", None)).total_seconds())
7374
def CPUFrequency():
7475
""" Refresh the CPU Frequency """
75-
# print("Refresh CPU Frequency")
76+
# logger.debug("Refresh CPU Frequency")
7677
stats.CPU.frequency()
7778

7879

7980
@async_job("CPU_Load")
8081
@schedule(timedelta(seconds=THEME_DATA['STATS']['CPU']['LOAD'].get("INTERVAL", None)).total_seconds())
8182
def CPULoad():
8283
""" Refresh the CPU Load """
83-
# print("Refresh CPU Load")
84+
# logger.debug("Refresh CPU Load")
8485
stats.CPU.load()
8586

8687

8788
@async_job("CPU_Load")
8889
@schedule(timedelta(seconds=THEME_DATA['STATS']['CPU']['TEMPERATURE'].get("INTERVAL", None)).total_seconds())
8990
def CPUTemperature():
9091
""" Refresh the CPU Temperature """
91-
# print("Refresh CPU Temperature")
92+
# logger.debug("Refresh CPU Temperature")
9293
stats.CPU.temperature()
9394

9495

9596
@async_job("GPU_Stats")
9697
@schedule(timedelta(seconds=THEME_DATA['STATS']['GPU'].get("INTERVAL", None)).total_seconds())
9798
def GpuNvidiaStats():
9899
""" Refresh the GPU Stats """
99-
# print("Refresh GPU Stats")
100+
# logger.debug("Refresh GPU Stats")
100101
stats.GpuNvidia.stats()
101102

102103

103104
@async_job("GPU_Stats")
104105
@schedule(timedelta(seconds=THEME_DATA['STATS']['GPU'].get("INTERVAL", None)).total_seconds())
105106
def GpuAmdStats():
106107
""" Refresh the GPU Stats """
107-
# print("Refresh GPU Stats")
108+
# logger.debug("Refresh GPU Stats")
108109
stats.GpuAmd.stats()
109110

110111

111112
@async_job("Memory_Stats")
112113
@schedule(timedelta(seconds=THEME_DATA['STATS']['MEMORY'].get("INTERVAL", None)).total_seconds())
113114
def MemoryStats():
114-
# print("Refresh memory stats")
115+
# logger.debug("Refresh memory stats")
115116
stats.Memory.stats()
116117

117118

118119
@async_job("Disk_Stats")
119120
@schedule(timedelta(seconds=THEME_DATA['STATS']['DISK'].get("INTERVAL", None)).total_seconds())
120121
def DiskStats():
121-
# print("Refresh disk stats")
122+
# logger.debug("Refresh disk stats")
122123
stats.Disk.stats()
123124

124125

library/stats.py

+5-4
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
import library.config as config
1010
from library.display import display
11+
from library.log import logger
1112

1213
THEME_DATA = config.THEME_DATA
1314

@@ -23,7 +24,7 @@ class CPU:
2324
@staticmethod
2425
def percentage():
2526
cpu_percentage = psutil.cpu_percent(interval=THEME_DATA['STATS']['CPU']['PERCENTAGE'].get("INTERVAL", None))
26-
# print(f"CPU Percentage: {cpu_percentage}")
27+
# logger.debug(f"CPU Percentage: {cpu_percentage}")
2728

2829
if THEME_DATA['STATS']['CPU']['PERCENTAGE']['TEXT'].get("SHOW", False):
2930
display.lcd.DisplayText(
@@ -80,7 +81,7 @@ def frequency():
8081
@staticmethod
8182
def load():
8283
cpu_load = psutil.getloadavg()
83-
# print(f"CPU Load: ({cpu_load[0]},{cpu_load[1]},{cpu_load[2]})")
84+
# logger.debug(f"CPU Load: ({cpu_load[0]},{cpu_load[1]},{cpu_load[2]})")
8485

8586
if THEME_DATA['STATS']['CPU']['LOAD']['ONE']['TEXT'].get("SHOW", False):
8687
display.lcd.DisplayText(
@@ -166,7 +167,7 @@ def temperature():
166167

167168
def display_gpu_stats(load, memory_percentage, memory_used, temperature):
168169
if THEME_DATA['STATS']['GPU']['PERCENTAGE']['GRAPH'].get("SHOW", False):
169-
# print(f"GPU Load: {load}")
170+
# logger.debug(f"GPU Load: {load}")
170171
display.lcd.DisplayProgressBar(
171172
x=THEME_DATA['STATS']['GPU']['PERCENTAGE']['GRAPH'].get("X", 0),
172173
y=THEME_DATA['STATS']['GPU']['PERCENTAGE']['GRAPH'].get("Y", 0),
@@ -198,7 +199,7 @@ def display_gpu_stats(load, memory_percentage, memory_used, temperature):
198199
)
199200

200201
if THEME_DATA['STATS']['GPU']['MEMORY']['GRAPH'].get("SHOW", False):
201-
# print(f"GPU Load: {load}")
202+
# logger.debug(f"GPU Load: {load}")
202203
display.lcd.DisplayProgressBar(
203204
x=THEME_DATA['STATS']['GPU']['MEMORY']['GRAPH'].get("X", 0),
204205
y=THEME_DATA['STATS']['GPU']['MEMORY']['GRAPH'].get("Y", 0),

main.py

+9-8
Original file line numberDiff line numberDiff line change
@@ -9,33 +9,34 @@
99

1010
MIN_PYTHON = (3, 7)
1111
if sys.version_info < MIN_PYTHON:
12-
print("Error: Python %s.%s or later is required.\n" % MIN_PYTHON)
12+
print("[ERROR] Python %s.%s or later is required." % MIN_PYTHON)
1313
try:
1414
sys.exit(0)
1515
except:
1616
os._exit(0)
1717

18+
from library.log import logger
1819
import library.scheduler as scheduler
1920
from library.display import display
2021

2122
if __name__ == "__main__":
2223

2324
def sighandler(signum, frame):
24-
print(" Caught signal", str(signum), ", exiting")
25+
logger.info(" Caught signal %d, exiting" % signum)
2526

2627
# Do not stop the program now in case data transmission was in progress
2728
# Instead, ask the scheduler to empty the action queue before stopping
2829
scheduler.STOPPING = True
2930

3031
# Allow 5 seconds max. delay in case scheduler is not responding
3132
wait_time = 5
32-
print("Waiting for all pending request to be sent to display (%ds max)..." % wait_time)
33+
logger.info("Waiting for all pending request to be sent to display (%ds max)..." % wait_time)
3334

3435
while not scheduler.is_queue_empty() and wait_time > 0:
3536
time.sleep(0.1)
3637
wait_time = wait_time - 0.1
3738

38-
print("(%.1fs)" % (5 - wait_time))
39+
logger.debug("(%.1fs)" % (5 - wait_time))
3940

4041
# We force the exit to avoid waiting for other scheduled tasks: they may have a long delay!
4142
try:
@@ -69,15 +70,15 @@ def sighandler(signum, frame):
6970
if stats.CPU.is_temperature_available():
7071
scheduler.CPUTemperature()
7172
else:
72-
print("STATS: Your CPU temperature is not supported yet")
73+
logger.warning("Your CPU temperature is not supported yet")
7374
if stats.GpuNvidia.is_available():
74-
print("Detected Nvidia GPU(s)")
75+
logger.info("Detected Nvidia GPU(s)")
7576
scheduler.GpuNvidiaStats()
7677
elif stats.GpuAmd.is_available():
77-
print("Detected AMD GPU(s)")
78+
logger.info("Detected AMD GPU(s)")
7879
scheduler.GpuAmdStats()
7980
else:
80-
print("STATS: Your GPU is not supported yet")
81+
logger.warning("Your GPU is not supported yet")
8182
scheduler.MemoryStats()
8283
scheduler.DiskStats()
8384
scheduler.QueueHandler()

0 commit comments

Comments
 (0)