Skip to content

Commit 00ba64d

Browse files
committed
Use logger instead of print
1 parent f2bc0b4 commit 00ba64d

File tree

2 files changed

+53
-47
lines changed

2 files changed

+53
-47
lines changed

riberry/battery/mp2760.py

+52-47
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,17 @@
11
from enum import Enum
2+
import logging
3+
import os
24
import threading
35
import time
46

57
import smbus2
68

79
from riberry.battery.common import majority_vote
810

11+
# Set up logging
12+
LOG_LEVEL = os.getenv('LOG_LEVEL', 'INFO').upper()
13+
logging.basicConfig(level=LOG_LEVEL)
14+
logger = logging.getLogger(__name__)
915

1016
class ChargeState(Enum):
1117
NO_CHARGE = 0
@@ -60,7 +66,7 @@ def print_status_and_fault_register(value):
6066
continue
6167
if (value >> bit) & 1:
6268
msg = f"Bit {bit}: {descriptions.get(bit, 'Unknown')}"
63-
print(msg)
69+
logger.info(msg)
6470
status_and_fault_list.append(msg)
6571
if len(status_and_fault_list) == 0:
6672
return "All green."
@@ -98,29 +104,29 @@ def __init__(
98104

99105
self.bus = smbus2.SMBus(self.bus_number)
100106
while self.disable_ntc_protection() is None:
101-
print("[MP2760BatteryMonitor] Try to disable NTC protection.")
107+
logger.warning("[MP2760BatteryMonitor] Try to disable NTC protection.")
102108
time.sleep(1.0)
103109
while self.set_adc_continuous_mode(set_bit=True) is None:
104-
print("[MP2760BatteryMonitor] Try to enable adc continuous mode.")
110+
logger.warning("[MP2760BatteryMonitor] Try to enable adc continuous mode.")
105111
time.sleep(1.0)
106112
while self.set_safety_timer(set_bit=True) is None:
107-
print("[MP2760BatteryMonitor] Try to enable safety timer.")
113+
logger.warning("[MP2760BatteryMonitor] Try to enable safety timer.")
108114
time.sleep(1.0)
109115
self.limit_charge_current(400)
110-
print(
116+
logger.info(
111117
"[MP2760BatteryMonitor] Charge current limit: ",
112118
f"{self.read_charge_current_limit()}[mA]",
113119
)
114120
self.limit_input_current(500)
115-
print(
121+
logger.info(
116122
"[MP2760BatteryMonitor] Input current limit: ",
117123
f"{self.read_input_current_limit()}[mA]",
118124
)
119125
self.lock = threading.Lock()
120126
self.running = True
121127

122128
def __del__(self):
123-
print("[MP2760BatteryMonitor] Object is being deleted, cleaning up...")
129+
logger.info("[MP2760BatteryMonitor] Object is being deleted, cleaning up...")
124130
self.stop()
125131
self.set_adc_continuous_mode(False)
126132
self.bus.close()
@@ -130,10 +136,10 @@ def exists(self, bus_number=3, device_address=0x5C):
130136
try:
131137
with smbus2.SMBus(bus_number) as bus:
132138
bus.read_byte(device_address)
133-
print("[MP2760BatteryMonitor] found.")
139+
logger.info("[MP2760BatteryMonitor] found.")
134140
return True
135141
except OSError as e:
136-
print(f"[MP2760BatteryMonitor] {e}. Device not found")
142+
logger.error(f"[MP2760BatteryMonitor] {e}. Device not found")
137143
return False
138144

139145
def is_outlier(self, current, history, threshold):
@@ -151,66 +157,66 @@ def set_adc_continuous_mode(self, set_bit=True):
151157
try:
152158
word = self.bus.read_word_data(self.device_address, 0x0E)
153159
except Exception as e:
154-
print(f"[Battery Monitor] Error reading from I2C: {e}")
160+
logger.error(f"[Battery Monitor] Error reading from I2C: {e}")
155161
return
156162
current_bit = (word >> 7) & 1
157163
if current_bit == set_bit:
158-
print(
159-
"[Battery Monitor] 7bit is already set to the desired value. ",
160-
"No action needed.",
164+
logger.info(
165+
"[Battery Monitor] 7bit is already set to the desired value. "
166+
+ "No action needed."
161167
)
162168
return True
163169
if set_bit:
164-
print("[Battery Monitor] Set ADC_CONV to Continuous")
170+
logger.info("[Battery Monitor] Set ADC_CONV to Continuous")
165171
set_adc_word = word | (1 << 7)
166172
else:
167-
print("[Battery Monitor] Set ADC_CONV to One-shot conversion")
173+
logger.info("[Battery Monitor] Set ADC_CONV to One-shot conversion")
168174
set_adc_word = word & ~(1 << 7)
169175
try:
170176
self.bus.write_word_data(self.device_address, 0x0E, set_adc_word)
171177
except Exception as e:
172-
print(f"[Battery Monitor] Error writing I2C: {e}")
178+
logger.error(f"[Battery Monitor] Error writing I2C: {e}")
173179
return
174180
return True
175181

176182
def disable_ntc_protection(self):
177183
try:
178184
word = self.bus.read_word_data(self.device_address, 0x0D)
179185
except Exception as e:
180-
print(f"[Battery Monitor] Error reading from I2C: {e}")
186+
logger.error(f"[Battery Monitor] Error reading from I2C: {e}")
181187
return
182188
current_bit = (word >> 9) & 1
183189
if current_bit == 0:
184-
print(
185-
"[Battery Monitor] 9bit is already set to the desired value. ",
186-
"No action needed.",
190+
logger.info(
191+
"[Battery Monitor] 9bit is already set to the desired value. "
192+
+ "No action needed."
187193
)
188194
return True
189-
print("[Battery Monitor] Disable NTC protection")
195+
logger.info("[Battery Monitor] Disable NTC protection")
190196
set_word = word & ~(1 << 9)
191197
try:
192198
self.bus.write_word_data(self.device_address, 0x0D, set_word)
193199
except Exception as e:
194-
print(f"[Battery Monitor] Error writing I2C: {e}")
200+
logger.error(f"[Battery Monitor] Error writing I2C: {e}")
195201
return
196202
return True
197203

198204
def set_safety_timer(self, set_bit=True):
199205
try:
200206
word = self.bus.read_word_data(self.device_address, 0x12)
201207
except Exception as e:
202-
print(f"[Battery Monitor] Error reading from I2C: {e}")
208+
logger.error(f"[Battery Monitor] Error reading from I2C: {e}")
203209
return
204210
if set_bit is True:
205-
print("[Battery Monitor] sefety timer is enabled.")
211+
logger.info("[Battery Monitor] Safety timer is enabled.")
206212
set_word = word | (1 << 13)
207213
else:
208-
print("[Battery Monitor] sefety timer is disabled.")
214+
logger.info("[Battery Monitor] Safety timer is disabled.")
209215
set_word = word & ~(1 << 13)
210216
try:
211217
self.bus.write_word_data(self.device_address, 0x12, set_word)
212218
except Exception as e:
213-
print(f"[Battery Monitor] Error writing I2C: {e}")
219+
logger.error(f"[Battery Monitor] Error writing I2C: {e}")
214220
return
215221
return True
216222

@@ -224,7 +230,7 @@ def limit_charge_current(self, set_current): # unit: [mA]
224230
or set_current < 50
225231
or set_current > 6000
226232
):
227-
print("[Battery Monitor] Charge current limit is not proper.")
233+
logger.error("[Battery Monitor] Charge current limit is not proper.")
228234
return
229235
for digit, current in zip(digits, currents):
230236
bit = set_current // current
@@ -233,7 +239,7 @@ def limit_charge_current(self, set_current): # unit: [mA]
233239
try:
234240
self.bus.write_word_data(self.device_address, 0x14, set_word)
235241
except Exception as e:
236-
print(f"[Battery Monitor] Error writing I2C: {e}")
242+
logger.error(f"[Battery Monitor] Error writing I2C: {e}")
237243
return
238244
return True
239245

@@ -247,7 +253,7 @@ def limit_input_current(self, set_current): # unit: [mA]
247253
or set_current < 50
248254
or set_current > 5000
249255
):
250-
print("[Battery Monitor] Input current limit is not proper.")
256+
logger.error("[Battery Monitor] Input current limit is not proper.")
251257
return
252258
for digit, current in zip(digits, currents):
253259
bit = set_current // current
@@ -256,24 +262,24 @@ def limit_input_current(self, set_current): # unit: [mA]
256262
try:
257263
self.bus.write_word_data(self.device_address, 0x08, set_word)
258264
except Exception as e:
259-
print(f"[Battery Monitor] Error writing I2C: {e}")
265+
logger.error(f"[Battery Monitor] Error writing I2C: {e}")
260266
return
261267
return True
262268

263269
def write_default_value_to_0x10_register(self):
264270
try:
265271
self.bus.write_word_data(self.device_address, 0x10, 0x0A74)
266-
print("[Battery Monitor] Successfully wrote 0x0A74 to register 0x10.")
272+
logger.info("[Battery Monitor] Successfully wrote 0x0A74 to register 0x10.")
267273
return True
268274
except Exception as e:
269-
print(f"[Battery Monitor] Error writing to register 0x10: {e}")
275+
logger.error(f"[Battery Monitor] Error writing to register 0x10: {e}")
270276
return False
271277

272278
def read_charge_current_limit(self): # unit: [mA]
273279
try:
274280
bits = self.bus.read_word_data(self.device_address, 0x14)
275281
except Exception as e:
276-
print(f"[Battery Monitor] Error reading from I2C: {e}")
282+
logger.error(f"[Battery Monitor] Error reading from I2C: {e}")
277283
return
278284
current = 0
279285
current += ((bits & 0x2000) >> 13) * 6400
@@ -290,7 +296,7 @@ def read_input_current_limit(self): # unit: [mA]
290296
try:
291297
bits = self.bus.read_word_data(self.device_address, 0x08)
292298
except Exception as e:
293-
print(f"[Battery Monitor] Error reading from I2C: {e}")
299+
logger.error(f"[Battery Monitor] Error reading from I2C: {e}")
294300
return
295301
current = 0
296302
current += ((bits & 0x0040) >> 6) * 3200
@@ -317,7 +323,7 @@ def read_register(self, register):
317323
try:
318324
value = self.bus.read_word_data(self.device_address, register)
319325
except Exception as e:
320-
print(f"[Battery Monitor] {e}")
326+
logger.error(f"[Battery Monitor] {e}")
321327
return None
322328
return value
323329

@@ -500,25 +506,24 @@ def run(self):
500506
self.battery_charge_current,
501507
) = self.read_sensor_data()
502508
if self.input_voltage:
503-
print(f"Input Voltage: {self.input_voltage:.2f} V")
509+
logger.info(f"Input Voltage: {self.input_voltage:.2f} V")
504510
if self.system_voltage:
505-
print("System Voltage: " f"{self.system_voltage:.2f} V")
511+
logger.info(f"System Voltage: {self.system_voltage:.2f} V")
506512
if self.battery_voltage:
507-
print("Battery Voltage: " f"{self.battery_voltage:.2f} V")
508-
print("Battery charge Current: " f"{self.battery_charge_current:.2f} mA")
513+
logger.info(f"Battery Voltage: {self.battery_voltage:.2f} V")
514+
logger.info(f"Battery charge Current: {self.battery_charge_current:.2f} mA")
509515
if self.junction_temperature:
510-
print("Junction Temperature: " f"{self.junction_temperature:.2f}")
516+
logger.info(f"Junction Temperature: {self.junction_temperature:.2f}")
511517
if percentage is None or is_charging is None:
512518
time.sleep(0.2)
513519
continue
514520
with self.lock:
515521
if self.is_outlier(
516522
percentage, self.percentage_history, self.percentage_threshold
517523
):
518-
print(
519-
"Percentage outlier detected:",
520-
f" {percentage:.2f}, ",
521-
f"history: {self.percentage_history}",
524+
logger.warning(
525+
f"Percentage outlier detected: {percentage:.2f}, "
526+
+ f"history: {self.percentage_history}"
522527
)
523528
else:
524529
self.filtered_percentage = (
@@ -533,9 +538,9 @@ def run(self):
533538
self.charging_history.pop(0)
534539

535540
if self.debug:
536-
print(f"RAW Percentage: {percentage:.2f}")
537-
print("Filtered Percentage:", f" {self.filtered_percentage:.2f}")
538-
print(f"Charge Status: {self.charge_status}")
541+
logger.debug(f"RAW Percentage: {percentage:.2f}")
542+
logger.debug(f"Filtered Percentage: {self.filtered_percentage:.2f}")
543+
logger.debug(f"Charge Status: {self.charge_status}")
539544
time.sleep(0.2)
540545
finally:
541546
self.bus.close()

systemd/display_information.service

+1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ Wants=network-online.target
44
After=network-online.target
55

66
[Service]
7+
Environment="LOG_LEVEL=DEBUG"
78
Type=simple
89
ExecStart=/usr/local/bin/run_display_information.sh
910
Restart=always

0 commit comments

Comments
 (0)